好的,这应该很简单,但我遇到了麻烦。我有两个类区域和位置。一个区域可以有多个位置,但一个位置只能在一个区域中。简单的东西。这是我所拥有的:
Location Region
--------- -------
int LocationID int RegionID
string Name string Name
string BlahBlah List<Location> Locations
string OtherStuff
int RegionID
Region Region
现在我需要在一个区域中添加一个家庭办公室。家庭办公室也是一个位置。 Entity Framework 似乎很困惑,所以我显然做错了事。这就是我想要做的:
Location Region
--------- -------
int LocationID int RegionID
string Name string Name
string BlahBlah List<Location> Locations
string OtherStuff int HomeOfficeID
int RegionID Location HomeOffice
Region Region
我在这里错过了什么?
如果你不喜欢我上面写的,这里有类:
public class Region
{
public int RegionID { get; set; }
public string Name { get; set; }
public int HomeOfficeID { get; set; }
public virtual Location HomeOffice { get; set; }
public virtual List<Location> Locations { get; set; }
}
public class Location
{
public int LocationID { get; set; }
public string Name { get; set; }
public int RegionID { get; set; }
public virtual Region Region { get; set; }
}
最佳答案
因此,如果“家庭办公室”除了任何其他位置之外确实没有其他数据,则有一个解决方法:
Location Region
--------- -------
int LocationID int RegionID
string Name string Name
string BlahBlah List<Location> Locations
string OtherStuff
int RegionID
Region Region
bool IsHomeOffice
现在,Region 获得一个只读属性:
public Location HomeOffice
{
get { return Locations.FirstOrDefault(l => l.IsHomeOffice); }
}
您还需要一些验证代码以确保您最终不会为 IsHomeOffice 分配多个位置,但这将帮助您开始。
编辑:评论让我意识到这种方法不允许 HomeOffice 位于所在区域之外。这会发生吗?最初的想法是不太可能,但也许“HomeOffice”真的意味着一个地区的人力资源人员所在的地方。现在 HomeOffice 总是在区域内,但在未来,公司可以决定远程为某个区域做 HR。在这个有限的示例中,适应起来不会太痛苦,但是随着您的数据模型变得越来越复杂,当您的数据模型的结构需要改变时,它会变得更加痛苦。与其总是依赖结构来执行规则,不如考虑保持结构的灵 active 并在输入时添加数据验证。
关于c# - EF代码优先关系的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537157/