你的资料库是要与不同类型的对导航属性过滤器返回实体的方法非常迅速填满。也许你应该有一个看起来像这样的方法:
public GetUser(int userid,
Expression<System.Func<Project, System.Boolean>> projectFilter,
Expression<System.Func<Exam, System.Boolean>> examFilter)
{
var user = context.Users.Find(userid);
context.Entry(user)
.Collection(c => c.Projects)
.Query()
.Where(projectFilter)
.Load();
context.Entry(user)
.Collection(c => c.Exams)
.Query()
.Where(examFilter)
.Load();
return user
}
你这样称呼它:
var userincludingCurrentProjectsAndExamsWithScoresLessThan4 =
userRepo.GetUser(id, p => p.Current, e => e.Score > 4)
而且不要忘了从集合或延迟加载删除virtual
关键字会拉整个集合了过滤器之前的数据库应用:
public class User
{
public int IdUser { get; set;}
public ICollection<Project> Projects { get; set;}
public ICollection<Exam> Exams { get; set;}
}
编辑 我不得不说,这种部分填充导航属性的技术对我来说有点有趣。我认为大多数人所做的工作是将数据投影到DTO或ViewModel中,以实现您正在尝试做的事情。然后,DTO的可以具有更有意义的属性名称。事情是这样的:
var query = from f in context.Foos.Include(x => x.Bars).Include(y => y.Bazs)
select new FooDTO
{
ID = f.ID,
Toms = f.Bars.Where(b => b.Name == "Tom").ToList(),
Dicks = f.Bazs.Where(b => b.Name == "Dick").ToList()
};
string sql = query.ToString();//useful in debugger. Remove once satisfied.
但是,如果你真的想投射到一个实体,而不是一个DTO你可以这样做:
var usersWithTomsAndDicksOohErr =
(from f in context.Foos.Include(x => x.Bars).Include(y => y.Bazs)
select new //anonymous. You can't construct entities using LINQ to Entities
{
ID = f.ID,
Toms = f.Bars.Where(b => b.Name == "Tom").ToList(),
Dicks = f.Bazs.Where(b => b.Name == "Dick").ToList()
})
.AsEnumerable()//moves only the data you want into memory
.Select(x => new Foo//now you can construct the entity using Linq to Objects
{
ID = x.ID,
Bars = x.Toms,
Bazs = x.Dicks
});
我觉得你还是获取完整的数据集,因为你的天堂” t删除了虚拟关键字http://stackoverflow.com/a/20358097/150342 – Colin