本文介绍了有多个共同父母的参照孩子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下数据结构:

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连接的Bar.所以我想做类似的事情:

What I want to do when querying the context is to include all the Bars that are joined either by FooOneId or FooTwoId. So I would like to do something like:

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

以便在我从数据库中检索Foo时包括所有关联的Bar.

in order to include all the associated Bars when I retrieve a Foo from the database.

但是当上下文构建模型时,出现以下异常:

But I get following exception when the context builds the model:

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

如果我删除FooTwoId和FwoTwo,则它具有简单的父/子关系,并且非常满意.

If I remove FooTwoId and FwoTwo then it has a simple Parent/Child relationship and is quite happy.

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

Any ideas how to do this? I don't mind if I have to have the list of Bars as two separate lists - I just want do this is a single database hit.

推荐答案

为什么不反转它并让Bar成为驱动程序?

Why not invert it and let Bar be the driver?

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

当然,您必须处理在接收端使用哪个Foo.

Of course, you would have to process which Foo to use in the receiving end.

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

This is actually a Many-to-Many relationship and should be designed that way. Arguably, this increases complexity but more accurately describes the relationship.

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();

这篇关于有多个共同父母的参照孩子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:33