实体框架核心中的条件导航属性

问题描述 投票:2回答:1

我正在尝试在EF Core中创建一个导航属性,它将根据两个属性的值有条件地设置其引用。我不确定这是否可行。

让我举个例子:让我说我有一个实体的层次结构,如CountryStateCountyCity。我还有一个名为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);

我真的不知道如何完成我在这里要做的事情。有任何想法吗?

c# .net-core entity-framework-core navigation-properties
1个回答
1
投票

我可以看到你有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的能力,并且可以轻松集成到外部逻辑中,包括单元测试。

© www.soinside.com 2019 - 2024. All rights reserved.