引用具有多个共同父项的子实体

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

我有以下数据结构:

public class Foo
{
    [Key]
    public int Id { get; set; }
    public IList<Bar> Bars { get; set; }
}
public class Bar
{
    [Key]
    public int Id { get; set;}
    public int FooOneId { get; set;}
    public int FooTwoId { get; set; }

    [ForeignKey("FooOneId")]
    public Foo FooOne { get; set; }
    [ForeignKey("FooTwoId")]
    public Foo FooFwo { get; set;}
}

查询上下文时我想要做的是包括由FooOneId或FooTwoId连接的所有Bars。所以我想做一些事情:

var foos = context.Foos.Where(f => f.Id == id).Include(f => f.Bars).ToList();

从数据库中检索Foo时包含所有关联的Bars。

但是当上下文构建模型时,我得到以下异常:

System.InvalidOperationException: Unable to determine the relationship
represented by navigation property 'Foo.Bars' of type 'IList<Bar>'

如果我删除FooTwoId和FwoTwo,那么它有一个简单的父/子关系并且非常高兴。

任何想法如何做到这一点?我不介意我是否必须将Bars列表作为两个单独的列表 - 我只是希望这是一个单一的数据库命中。

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

为什么不颠倒它并让Bar成为司机呢?

var bars = context.Bars.Where(f => f.Foo1Id == id || f.Foo2Id == id).Include("FooOne").Include("FooTwo").ToList();

当然,您必须处理在接收端使用哪种食物。

这实际上是一个多对多的关系,应该以这种方式设计。可以说,这增加了复杂性,但更准确地描述了这种关系。

public class Foo
{
    [Key]
    public int Id { get; set; }

    public IList<FooBar> Bars { get; set; }
}
public class Bar
{
    [Key]
    public int Id { get; set;}

    public IList<FooBar> Foos { get; set;}
}
public class FooBar
{
    [Key]
    public int Id { get; set; }
    public int FooId { get; set; }
    public int BarId { get; set; }

    [ForeignKey("FooId")]
    public Foo Foo { get; set; }
    [ForeignKey("BarId")]
    public Bar Bar { get; set;}
}

context.FooBar.Where(f => f.FooId == id).Include("Foo").Include("Bar").ToList();

要么

context.Foo.Where(f => f.Id == id).Include("FooBar").Include("FooBar.Bar").ToList();
© www.soinside.com 2019 - 2024. All rights reserved.