[英]EF Fluent API one-to-many relationship. On what end should I define it?
使用Entity Framework Fluent API,可以在两个参与的类上定义关系。 我想知道这两种解决方案是否有优缺点。
让我示范一下。 我有这些课:
public class GroupOfAnimals
{
public int ID { get; set; }
public virtual ICollection<Animal> Members { get; set; }
}
public class Animal
{
public int ID { get; set; }
public int GroupID { get; set; }
public virtual GroupOfAnimals Group { get; set; }
}
以及配置:
public class GroupOfAnimalsConfiguration : EntityTypeConfiguration<GroupOfAnimals>
{
public GroupOfAnimalsConfiguration ()
{
HasKey(o => o.ID);
//Defining relationship #1
HasMany(o => o.Members)
.WithRequired(o => o.Group)
.HasForeignKey(o => o.GroupID);
}
}
public class AnimalConfiguration : EntityTypeConfiguration<Animal>
{
public AnimalConfiguration()
{
HasKey(o => o.ID);
//Defining relationship #2
HasRequired(o => o.Group)
.WithMany(o => o.Members)
.HasForeignKey(o => o.GroupID);
}
}
如您所见,两种配置都包含相同的一对多关系。 这显然是多余的。
相比之下,使用属性可以很清楚地看出在以下情况下的去向:
public class GroupOfAnimals
{
[Key]
public int ID { get; set; }
[InverseProperty("Group")]
public virtual ICollection<Animal> Members { get; set; }
}
public class Animal
{
[Key]
public int ID { get; set; }
[ForeignKey("Group ")]
public int GroupID { get; set; }
[InverseProperty("Members")]
public virtual GroupOfAnimals Group { get; set; }
}
我的问题是:
我应该在哪里定义关系? 在组上? 在动物身上? 有什么区别吗? 我在这里应该遵循明确的约定吗?
关系可以在任一端定义。 具体取决于您要执行的操作,但是无论选择哪种方式,都应该保持一致。
使用一种或另一种方式没有优势,它们只是给您灵活性,以您认为最有意义的方式定义它们。 无论哪种方式,您最终都将拥有相同的关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.