问题描述
|
我有以下Entity Framework 4.1实体和关系
音乐会ConcertId,AdministratorUserId,名称,IsDeleted
订票
BookingId,ConcertId,UserId,IsDeleted
用户ID,用户ID,名称,已删除
人际关系
音乐会1 ..... M预订1 .... 1用户
现在,我正在尝试为特定的AdminstratorUserId选择所有音乐会,还包括每个音乐会的所有预订以及每个预订的用户详细信息。我还想对每个音乐会,预订和用户使用IsDeleted == false的过滤器。我想返回一个音乐会列表,这些音乐会的预订和用户详细信息都保留为导航属性。
在sql中,这就是我要实现的目标:
SELECT *
FROM concert c,booking b,user u
WHERE c.ConcertId = b.ConcertId AND b.UserId = u.UserId AND c.AdministratorId = 10
AND c.IsDeleted = false AND b.IsDeleted = false AND u.IsDeleted = false
据我所知,使用\“ Include \”方法渴望加载,不允许对其加载的子实体进行过滤或子查询。它返回该连接的所有记录,因此我尝试使用匿名投影,如下所示:
int adminId = 10;
var concerts = _context.Concerts
.Where(p => p.AdministratorId == adminId && p.IsDeleted == false)
.Select(p => new {
Concerts = p,Bookings = p.Bookings
.Where(q => q.IsDeleted == false && q.User.IsDeleted == false)
.Select(r => new {
Bookings = r,User = r.User
})
.AsEnumerable()
.Select(q => q.Bookings)
})
.AsEnumerable()
.Select(p => p.Concerts)
.ToList();
但是,这仍然返回所有记录,而不是过滤掉IsDeleted = true的记录。任何人都有任何想法或建议,我该如何清理这个可怕的查询?
我也尝试过类似的方法(http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx) ,再次失败(返回所有预订,甚至删除的预订):
var concertsQuery = (ObjectQuery<Concert>)_context.Concerts
.Where(p => p.UserId == userId
&& p.IsDeleted == false
&& p.Bookings.Any(q => q.IsDeleted == false && q.User.IsDeleted == false)
);
var concerts = concertsQuery.Include(\"Bookings\").Include(\"Bookings.User\").ToList();
解决方法
摆脱那些“ 3”,它们会将您的查询变成linq-to-objects:
var concerts = _context.Concerts
.Where(p => p.AdministratorId == adminId && p.IsDeleted == false)
.Select(p => new {
Concerts = p,Bookings = p.Bookings
.Where(q => q.IsDeleted == false && q.User.IsDeleted == false)
.Select(r => new {
Bookings = r,User = r.User
})
})
.ToList();
, 因此,我设法解决此问题的方法是按照Ladislav的回答运行LINQ查询,然后使用匿名对象将各个对象重新附加到其正确的关系属性,如下所示:
var concertResult = new List<Concert>();
foreach (var concertObject in concerts)
{
var concert = concertObject.Concert;
foreach (var bookingObject in concertObject.Bookings)
{
var booking = bookingObject.Booking;
booking.User = bookingObject.User;
concert.Bookings.Add(booking);
}
concertResult.Add(concert);
}