首先在ef代码中查询三个(或更多)多对多相关实体

时间:2012-08-31 10:37:14

标签: entity-framework ef-code-first

我在.net4.0中使用EF5.0并且我有三个具有多对多关系的实体,如下所示:

    public class A
    {
        public int Id { get; set; }
        public ICollection<B> Bs { get; set; }
    }
    public class B
    {
        public int Id { get; set; }
        public ICollection<A> As { get; set; }
        public ICollection<C> Cs { get; set; }
    }
    public class C
    {
        public int Id { get; set; }
        public ICollection<B> Bs { get; set; }
    }

这是我的映射代码:

        HasMany(a => a.Bs).WithMany(b => b.As).Map(m =>
        {
            m.ToTable("A_B");
        });

        HasMany(c => c.Bs).WithMany(b => b.Cs).Map(m =>
        {
            m.ToTable("B_C");
        });

对于某个A的实例,我怎样才能得到所有与B间接相关的C?

我想得到一个干净的SQL查询,如:

select C.* from C 
join B_C on B_C.Cid = C.id
join A_B on A_B.Bid = B_C.Bid
join A on A.id = A_B.Aid
where A.id = 1

Coude我得到那个sql而没有给联结表一个实体类型? 我的代码下面有一个非常难看的嵌套查询的SQL:

var res = Context.C.Where(
                 c => c.Bs.SelectMany(b => b.As.Select(a => a.Id))
                          .Contains(theA.Id)
                     );

请帮助我,非常感谢!

1 个答案:

答案 0 :(得分:0)

我会尝试这个查询:

var res = Context.C.Where(c => c.Bs.Any(b => b.As.Any(a => a.Id == theA.Id)));