我正在尝试在EF Core中创建一个导航属性,它将根据两个属性的值有条件地设置其引用。我不确定这是否可行。
让我举个例子:让我说我有一个实体的层次结构,如Country
,State
,County
和City
。我还有一个名为Law
的实体,它可以由任何分层实体“拥有”。
所以,我创建了这个枚举:
public enum OwnerType
{
Country,
State,
County,
City
}
......和Law
班:
public class Law
{
public int Id { get; set; }
public OwnerType OwnerType { get; set; }
public int OwnerId { get; set; }
}
现在我想设置Law
类,使其具有一个导航属性,该属性可以根据OwnerId
值将OwnerType
链接到相应实体的主键。
我考虑将此添加到Law
类:
public virtual object Owner { get; set; }
或者创建一个IOwner
接口,每个分层实体将实现,然后我添加它:
public virtual IOwner Owner { get; set; }
但后来我不知道如何用EntityTypeConfiguration
设置EntityTypeBuilder
。这显然不起作用:
builder.HasOne(x => x.Owner).WithMany(x => x.Laws).HasForeignKey(x => x.OwnerId);
我真的不知道如何完成我在这里要做的事情。有任何想法吗?
我可以看到你有4种不同的关系,你想用一个外键处理它们,这在概念上是个坏主意。如果你有4个关系 - 你需要有4个FK。
在纯OOP中你可以使用和IOwner
接口,但实体框架需要显式信息来分别映射你的关系,我相信这是最好的方法。只需添加4个不同的可空FK,并使用Law
值验证OwnerType
状态。
public class Law {
public int Id { get; set; }
public OwnerType OwnerType { get; set; }
[ForeignKey(nameof(Country)]
public int? CountryId { get; set; }
public Country Country { get; set; }
[ForeignKey(nameof(State)]
public int? StateId { get; set; }
public State State { get; set; }
[ForeignKey(nameof(County)]
public int? CountyId { get; set; }
public County County { get; set; }
[ForeignKey(nameof(City)]
public int? CityId { get; set; }
public City City { get; set; }
private void Validate() {
switch (OwnerType)
{
case OwnerType.Coutnry:
if(CountryId == null)
throw new LawValidationException("Country is requried");
break;
case OwnerType.State:
if(StateId == null)
throw new LawValidationException("State is requried");
break;
case OwnerType.County:
if(CountyId == null)
throw new LawValidationException("County is requried");
break;
case OwnerType.City:
if(CityId == null)
throw new LawValidationException("City is requried");
break;
default:
throw new LawValidationException("Invalid law owner type");
}
}
}
这种方法可以解决您的问题,完全符合Entity Framework的能力,并且可以轻松集成到外部逻辑中,包括单元测试。