如何建立正确的代码优先关系

时间:2014-05-02 19:47:11

标签: c# entity-framework code-first

我对Entity Framework相当新,并且使用Code-First模式而不是DB-First感觉更有控制力。

我想知道在以编程方式设置实体之间的ForeignKey关系时更倾向于什么。

在类中声明与另一个类相关的FK_属性是否更好?或者更好地在与之相关的类中声明IEnumerable<>属性?

public class IRelateToAnotherClass
{
    ...
    public int FK_IGetRelatedToByAnotherClass_ID { get; set; }
}

public class IGetRelatedToByAnotherClass
{
    ...
    public IEnumerable<IRelateToAnotherClass> RelatedTo { get; set; }
}

2 个答案:

答案 0 :(得分:2)

这完全取决于您的实体之间需要什么类型的关系(一对一,一对多,多对多);但是,是的,您应该声明外键属性。查看此网站for some examples

这是您的两个班级的一对多:

public class IRelateToAnotherClass
{
    public int Id { get; set; } // primary key
    public virtual ICollection<IGetRelatedToByAnotherClass> IGetRelatedToByAnotherClasses { get; set; }
}

public class IGetRelatedToByAnotherClass
{
    public int Id { get; set; } // primary key
    public int IRelateToAnotherClassId { get; set; } // foreign key
    public virtual IRelateToAnotherClass IRelateToAnotherClass { get; set; }
}

并使用一些Fluent API映射:

modelBuilder.Entity<IGetRelatedToByAnotherClass>.HasRequired<IRelateToAnotherClass>(p => p.IRelateToAnotherClass).WithMany(p => p.IGetRelatedToByAnotherClasses).HasForeignKey(p => p.Id);

答案 1 :(得分:2)

如果我理解你的问题是正确的,你需要两者。你想要一个int FK属性和一个对象属性用作导航属性。

最终结果如下所示:

public class Employee
{
    [Key]
    public int EmployeeID { get; set; }

    [ForeignKey("Store")]
    public int StoreNumber { get; set; }

    // Navigation Properties
    public virtual Store Store { get; set; }
}

public class Store
{
    [Key]
    public int StoreNumber { get; set; }

    // Navigation Properties   
    public virtual List<Employee> Employees { get; set; }
}


如果您还没有,请查看navigation properties和延迟加载。请注意,EF足够聪明,可以确定int StoreID属性对应于对象Store属性,但如果它们的名称不同(例如没有ID后缀),则必须使用[ForeignKey] annotation