引用具有多个共同父级的子实体 [英] Reference child entity with multiple common parents

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

问题描述

我有以下数据结构:

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

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 时包含所有关联的 Bars.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆