
[英]Is it possible to make entities from two different edmx's map to the same class in Entity Framework?
[英]Can one Entity contain two different Entities of the same type, uniquely accessible?
暂时忘记数据库和表。 说我有一类Spaceship
和一类Person
。 如果我正在编写Contract
模型,则可以这样做:
public class Spaceship {
public string LicensePlate { get; set; } //
public string Destination { get; set; } //Regular old data
public Person Captain { get; set; }
public Person Engineer { get; set; }
}
因为队长和工程师都是人,虽然他们的相关信息可能略有不同,但是如果他们是同一类型,他们将保持最大的干燥状态。
但是,如果我想在实体框架中建立这种关系怎么办? 如果我是在Entity Designer中进行草拟的,我将建立如下关系:
--------------------- ---------------------
| Spaceship | | Person |
|---------------------| |---------------------|
| LicensePlate | | Name |
| Destination | | PhoneNumber |
|---------------------| |---------------------|
|Navigation Properties| |Navigation Properties|
| People |1---------------*| Spaceship |
--------------------- ---------------------
但这不是同一回事。 因为尽管两个People
可以准确地共享同一阶级,但他们与Spaceship
的关系却根本不同。 我想拥有一个dbContext,我可以说
Spaceship Enterprise = new Spaceship();
Enterprise.Captain = People.Find("Kirk");
Enterprise.Engineer = People.Find("Scotty");
那是过分的要求? 我的意思是,当然,还有其他方法。 Person
的Role
可能是“ Captain”或“ Engineer”,然后您可以将它们全部整合到Enterprise.People
。 如果您需要大量访问船长,甚至可以在Spaceship
上创建GetCaptain()
方法。
但是,为了教育的利益,
您可以添加与Person表具有零或一对一关系的Engineer和Captain表,这将为您提供两个关于飞船的导航属性。 如果您的模型发生更改并且子类型最终需要新的属性或方法,则此方法可能很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.