我有以下数据结构:
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时包含所有关联的条。
但是当上下文构建模型时,我得到以下异常:
System.InvalidOperationException: Unable to determine the relationship
represented by navigation property 'Foo.Bars' of type 'IList<Bar>'
如果我删除FooTwoId和FwoTwo,那么它有一个简单的父/子关系并且非常高兴。
任何想法如何做到这一点?如果我必须将Bars列表作为两个单独的列表,我不介意 - 我只是希望这是一个单独的数据库命中。
答案 0 :(得分:1)
为什么不将它倒置并让Bar成为司机?
var bars = context.Bars.Where(f => f.Foo1Id == id || f.Foo2Id == id).Include("FooOne").Include("FooTwo").ToList();
当然,您必须处理在接收端使用哪个Foo。
这实际上是一个多对多的关系,应该以这种方式设计。可以说,这增加了复杂性,但更准确地描述了这种关系。
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();