[英]Entity Framework messes up my many-to-many self relation
I have a Products Table and a BundleLink Table which defines whicht product is a bundle product of an other. 我有一个产品表和一个BundleLink表,它们定义了哪个产品是另一个产品的捆绑产品。
public class Product
{
public int Id { get; set; }
public ICollection<BundleLink> MasterOf { get; set; }
public ICollection<BundleLink> BundleOf { get; set; }
}
public class BundleLink
{
public int Id { get; set; }
public Product Master { get; set; }
public Product Bundle { get; set; }
public int Quantity { get; set; }
}
So when I go to a master product, I see what bundles are referring to it and in the other direction. 因此,当我使用主产品时,我会看到捆绑在指什么产品,以及其他方向。
But entity framework creates 4 columns in the sql server in the BundleLink table. 但是实体框架在BundleLink表的sql服务器中创建4列。 It creates one for the product fields i defined and two more foreign keys where one of them is null everytime, it depends on in which direction i add a bundle.
它为我定义的产品字段创建一个,再创建两个外键,其中每个外键每次都为null,这取决于我添加捆绑的方向。 How can i define for EF which BundeLink collection belongs to which Product?
如何为EF定义哪个BundeLink集合属于哪个产品?
I hope my description is understandable. 我希望我的描述是可以理解的。 Thanks in advance.
提前致谢。
In Entity Framework you need to follow Data Annotations - ForeignKey Attribute in EF 6 & EF Core. 在实体框架中,您需要遵循EF 6和EF Core中的数据注释-ForeignKey属性。
The ForeignKey attribute is used to configure a foreign key in the relationship between two entities in EF 6 and EF Core. ForeignKey属性用于在EF 6和EF Core中的两个实体之间的关系中配置外键。 It overrides the default conventions.
它会覆盖默认约定。 As per the default convention, EF makes a property as foreign key property when its name matches with the primary key property of a related entity.
根据默认约定,当EF的名称与相关实体的主键属性匹配时,EF会将其作为外键属性。
More information: http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx 详细信息: http : //www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
Thanks, raghu 谢谢raghu
How can i define for EF which BundeLink collection belongs to which Product?
如何为EF定义哪个BundeLink集合属于哪个产品?
You have two solutions: 您有两种解决方案:
OnModelCreating
method of your DbConext
use fluent configuration so by defining relation it helps EF to know which collections belong to which. OnModelCreating
你的方法DbConext
用流利的配置,以便通过定义关系有助于EF知道哪些集合属于哪个。 InverseProperty
attribute. InverseProperty
属性装饰您的收藏集。 So in your collections you will have InversProperty("Master")
for MasterOf
collection and InversProperty("Bundle")
for BundleOf
. InversProperty("Master")
的MasterOf
收集和InversProperty("Bundle")
的BundleOf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.