[英]Conditional navigation properties in Entity Framework Core
我正在尝试在 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
类设置为具有导航属性,该属性将根据OwnerType
值将OwnerId
链接到相应实体的主键。
我考虑将其添加到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 并使用OwnerType
值验证Law
状态。
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");
}
}
}
这种方法可以解决您的问题,非常适合实体框架功能,并且可以轻松集成到包括单元测试在内的外部逻辑中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.