load navigation properties with filter for Entity Framework 4.3

后端 未结 1 959
眼角桃花
眼角桃花 2021-01-28 19:43

Few days back I put a question regarding mapping two classes Message and MessageStatusHistory using EF. The mapping is going fine but I am facing some

1条回答
  •  再見小時候
    2021-01-28 20:05

    About your EDIT part: You cannot use ToList() in a projection, just leave it an IEnumerable and convert to a List when you construct the Message. You also don't need to create two list objects, you can switch from the LINQ to Entities query to LINQ to Objects (the second Select) by using AsEnumerable():

    var list = (from m in _repository.DBSet
                where m.MessageIdentifier == id
                select new {
                    // ...
                    Histories = m.Histories.Where(x => x.SenderId == userId)
                })
                .AsEnumerable() // database query is executed here
                .Select(m => new Message {
                    // ...
                    Histories = m.Histories.ToList(),
                    // ...
                }).ToList();
    
    return list;
    

    Be aware that Include has no effect when you use a projection with select. You need to make the properties that you want to include part of the projection - as you already did with select new { Histories.....

    0 讨论(0)
提交回复
热议问题