【发布时间】:2016-04-18 11:41:36
【问题描述】:
我的目标是只访问一次数据库,并通过过滤的子集合获取订单。
为了实现这一点,我使用了投影:
using (var db = new context())
{
var query = from o in db.Orders
select
new
{
Order = o,
Events = o.Events.Where(
e => e.SomeBool
&& e.SomeBool2
),
EventsGroups = o.Events.Where(
e => e.SomeBool
&& e.SomeBool2
).Select(e => e.Groups),
};
}
这里的问题是子集合“组”事件没有加载。为了解决这个问题,我在查询中将它作为另一个属性“EventsGroups”加载,然后我可以将其与事件放在一起。
我的问题:有没有办法将孩子“组”直接加载到“事件”上,这样我就不必将它们作为另一个属性获取?
沿线
Events = o.Events.Where(
e => e.SomeBool
&& e.SomeBool2
).Include(e => e.Groups), //this cannot be done this way
为什么我使用投影而不是预先加载:
https://msdn.microsoft.com/en-us/magazine/hh205756.aspx
Filtering include items in LINQ and Entity Framework
底层类:
public class Order
{
public Order()
{
Events = new HashSet<Event>();
}
public int Id { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public Event()
{
Groups = new HashSet<Group>();
}
public int Id { get; set; }
public bool SomeBool { get; set; }
public bool SomeBool2 { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
public class Group
{
public Group()
{
Events = new HashSet<Event>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
【问题讨论】:
-
你可以试试
o.Events.include(e => e.Groups).Where(...吗? -
你的意思是在投影里面?我不相信 Include 存在那里imgur.com/ZOOXx0E
-
对不起,我认为@Ivans 下面的回答应该可以工作
标签: c# entity-framework linq projection anonymous-types