仅在不为null的情况下,如何渴望通过Include()加载?

时间:2018-12-19 07:31:54

标签: c# sql entity-framework

我正在尝试:

var abc = Context.PersonSet.Include(p=>p.Child).ToList();

但并非所有人都有一个孩子。所以我得到:

Type Error 我想获取所有的Persons,并且如果Child不为空,则希望包含它。将Child包含为null也可以。

6 个答案:

答案 0 :(得分:3)

返回空孩子而不是空

 Context.PersonSet.Include(a => ((a.Child == null) ? new Collection<Child>() : a.Child));

答案 1 :(得分:1)

您可以使用GroupJoin来获取所有人并加载他们的孩子(如果他们有孩子): (请考虑使用这种方法,您应在上下文中拥有DbSet of Children)

Context.PersonSet.GroupJoin(Context.Children, p => p.Id, c => c.PersonId, (p, c) =>
                 new { Person = p, Child = c }).ToList();

答案 2 :(得分:1)

I don't know why people keep upvoting the solutions like this:

Include(p => p.NavProp ?? new List<NavPropType>())

Because that won't work, that is invalid for Include():

InvalidOperationException:

The Include property lambda expression p => (p.NavProp ?? value(System.Collections.Generic.List'1[NavPropType])) is invalid. The expression should represent a property access: t => t.MyProperty.

To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. (Derived d) => d.MyProperty. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

The solution: declare your property with a default value:

public class Foo
{
    public List<Bar> Bars { get; set; } = new List<Bar>();
}

This makes sure Bars won't be null when no related records are found.

答案 3 :(得分:0)

该异常不应来自该行。 Include()应该使用LEFT JOIN来完成您所要的操作:“我想获得所有的Persons,如果Child不为null,我想包含它” 。要确认这一点,请检查从LINQ生成的SQL。

要解决此问题,请查看使用查询abc的结果的代码,并查看其是否正确处理了Child集合(即检查集合是否为空)。 / p>

答案 4 :(得分:0)

您只需使用null-coalescing operator

var abc = Context.PersonSet.Include(p => p.Child ?? new Collection<Child>());

如果a.Child不为null,则返回左操作数a.Child, 否则返回右手操作数,它是Collection中的Child

答案 5 :(得分:-1)

您可以尝试以下方法:

var abc = Context.PersonSet.Include(p=>p.Child).Where(p=>p.Child!=null).ToList();