实体框架代码首先共享1对多实体 [英] entity framework code first - shared 1-to-many entity
问题描述
我已经在这个街区过了几次,所以我采取了一个新的方法。我想知道是否可能有一个单一的实体在多个0对多关系的许多方面。这是我想要做的:
I've been going around the block a couple of times on this, so I'm taking a fresh approach. I would like to figure out if it possible to have a single entity that is on the many-side of multiple 0-to-many relationships. This is what I'm trying to do:
客户端有0到多个手机
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientId { get; set; }
public string Name { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
}
业务有0到多个手机
public class Business
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BusinessId { get; set; }
public string Name { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
}
这里是手机:
public class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhoneId { get; set; }
public string Number { get; set; }
}
当然,Business / Client中的电话属性的问题是这使FK在电话中成为客户端和商务客户端,这些手机连接在一起。
Of course, the problem with the Phones property in Business/Client is that this creates FK's in Phone to both Client and Business, which clutters-up Phones.
所以,我看到另一个海报尝试创建手动连接表,但似乎是适合多方参与一种关系:
So, I saw another poster try creating a manual join table, but it seemed to be geared to the many-side participating in one relationship:
public class ClientPhone
{
public int ClientID { get; set; }
public int PhoneID { get; set; }
public virtual Client Client { get; set; } // One Client
public virtual Phone Phone { get; set; } // One Phone
}
我应该把Phone分成ClientPhones和BusinessPhones吗使用传统的0对多关系的实体。如果有人可以给我一些建议,以最干净的方式来建模,这将是非常感谢。
Should I split Phone up into ClientPhones and BusinessPhones 'normal' entities using traditional 0-to-many relationships. If someone could give me some advice on the cleanest way to to model this, it would be very appreciated.
谢谢!
推荐答案
我想你可以使用每个层次化方法的表来建模,
I think you can model this using table per hierarchy method ,
public class Client
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientId { get; set; }
public string Name { get; set; }
public virtual ICollection<ClientPhone> Phones { get; set; }
}
public class Business
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BusinessId { get; set; }
public string Name { get; set; }
public virtual ICollection<BusinesPhone> Phones { get; set; }
}
public class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhoneId { get; set; }
public string Number { get; set; }
}
public class BusinesPhone:Phone
{
}
public class ClientPhone:Phone
{
}
这将为客户端和商务电话创建一个表带有鉴别器列。然后,您可以轻松分离客户端和商务手机。
This will create one table for both client and business phone with a discriminator column. Then you can easily separate client and business phones.
这篇关于实体框架代码首先共享1对多实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!