首先使用代码与现有数据库的关系

时间:2011-09-29 12:06:48

标签: entity-framework-4.1 entity-relationship code-first

定义两种类型之间的关系时,在两种类型中包含导航属性很重要,例如在以下示例中:

    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public Category Category { get; set; }
    }

    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public ICollection<Product> Products { get; set; }
    }

我可以不在类别中包含导航属性吗?

1 个答案:

答案 0 :(得分:1)

如果您只是想通过代码优先约定,那么是的,您需要两者都有。我还将该集合设置为“虚拟”以支持延迟加载。

您可以在构建模型时使用流畅配置进行设置。它会是这样的

modelBuilder.Entity<Product>()
    .HasMany(x => x.Category) 
相关问题