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);
}
}
ご覧のとおり、両方の構成に同じ 1 対多の関係が含まれています。これは明らかに冗長です。
対照的に、属性を使用すると、次のような状況で何がどこに行くのかが明確になります。
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; }
}
私の質問は:
関係をどこで定義する必要がありますか? グループで?動物に?違いはありますか?ここで従うべき明確な規則はありますか?