实体框架 - 如何过滤渴望加载的导航/关系属性?

时间:2011-06-23 09:53:55

标签: sql linq entity-framework c#-4.0

我有以下Entity Framework 4.1实体和关系

音乐会 ConcertId,AdministratorUserId,Name,IsDeleted

预订 BookingId,ConcertId,UserId,IsDeleted

UserId ,UserId,Name,IsDeleted

关系 音乐会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();

2 个答案:

答案 0 :(得分:2)

摆脱那些AsEnumerable他们会将您的查询转换为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();

答案 1 :(得分:1)

所以,我设法解决这个问题的方法是按照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);
}