相同类型的EF Core子集合

时间:2018-11-06 22:22:07

标签: c# asp.net-core entity-framework-core

给出以下类,如何获得EF Core来映射我的两个集合?

public class Foo
{
    public int FooId { get; set; }
    public List<Bar> BarWithTypeA { get; set; }
    public List<Bar> BarWithTypeB { get; set; }
}

public class Bar
{
    public int BarId { get; set; }
    public int FooId { get; set; }
    public int BarType { get; set; }
}

EF Core不允许您这样做(这是我的第一个想法):

_context.Foos.Inclue(x => x.BarWithTypeA.Where(w => w.BarType == 1);

我也尝试添加全局查询过滤器,但没有成功。我敢肯定这很简单,但是我正需要一副崭新的眼睛。

2 个答案:

答案 0 :(得分:1)

就您的数据库布局而言,FooBar之间没有两个链接,只有一个链接,因此您的实体应与之匹配:

public class Foo
{
    public int FooId { get; set; }
    public List<Bar> Bars { get; set; }
}

如果您确实想要这两个属性,则可以这样模拟它们:

[NotMapped]
public List<Bar> BarWithTypeA => Bars.Where(b => b.BarType == 1);
[NotMapped]
public List<Bar> BarWithTypeB => Bars.Where(b => b.BarType == 2);

答案 1 :(得分:1)

在SQL环境中没有完美的方法可以做到这一点。对于每种类型,您可以在Bar类上有两个可选的FooId:

public class Bar
{
    public int BarId { get; set; }
    public int? FooIdWhenTypeA { get; set; }
    public int? FooIdWhenTypeB { get; set; }
    public int BarType { get; set; }
}

但是我建议实际上是在客户端消除歧义:

public class Foo
{
    public int FooId { get; set; }
    public List<Bar> Bars { get; set; }

    [NotMapped]
    public List<Bar> BarWithTypeA { get => Bars.Where(x => x.BarType == 1).ToList() }

    [NotMapped]
    public List<Bar> BarWithTypeB { get => Bars.Where(x => x.BarType == 2).ToList() }
}
相关问题