简体   繁体   English

实体框架代码具有指向单个表的多个一对多关系的第一个配置

[英]Entity Framework Code First configuration with multiple one-to-many relationships pointing to a single table

I am building an application with many different objects (tables), many of which have a need to have a one-to-many relationship to an "Attribute" object. 我正在构建一个具有许多不同对象(表)的应用程序,其中许多对象需要与“属性”对象具有一对多的关系。 For example, I could have five different objects - A, B, C, D, E - and each of these needs to have an Attributes property - A.Attributes, B.Attributes, etc. 例如,我可以有五个不同的对象--A,B,C,D,E - 并且每个对象都需要具有Attributes属性 - A.Attributes,B.Attributes等。

My question is, how would be the best way to structure this in EF Code First? 我的问题是,如何在EF Code First中构建此代码的最佳方法是什么? This Attribute class may end up having 15-20 different classes that have a relationship with it. 此Attribute类最终可能包含15-20个与之关系的不同类。

Currently, a configuration for one of the "parent" classes looks like this: 目前,其中一个“父”类的配置如下所示:

        HasMany(rdp => rdp.Attributes)
            .WithOptional()
            .WillCascadeOnDelete();

However, this will create a foreign key column on the Attribute table (eg, "A_Id", "B_Id", etc). 但是,这将在Attribute表上创建一个外键列(例如,“A_Id”,“B_Id”等)。 So if I have 20 different classes with attributes, the Attribute table will have 20 different foreign keys. 因此,如果我有20个具有属性的不同类,则Attribute表将具有20个不同的外键。

Is there any better way to structure this? 有没有更好的方法来构建它?

You could introduce an AttributeList type that maps to its own table. 您可以引入映射到其自己的表的AttributeList类型。 Ie you could model the list as an entity. 即您可以将列表建模为实体。

A, B, C, D, E would have a one-to-one association to the AttributeList, with the foreign key to the AttributeList on the A, B, C, D and E classes. A,B,C,D,E与AttributeList具有一对一的关联,并且具有A,B,C,D和E类的AttributeList的外键。

Each AttributeList object contains many attributes, or in other words there is a one-to-many relationship from AttributeList to Attribute. 每个AttributeList对象包含许多属性,换句话说,从AttributeList到Attribute之间存在一对多关系。

Now you have a single type with one-to-many to the Attributes and you only need a single foreign key to the AttributeList on the attributes. 现在,您拥有一个具有属性的一对多的类型,并且您只需要属性上的AttributeList的单个外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM