你的資料庫是要與不同類型的對導航屬性過濾器返回實體的方法非常迅速填滿。也許你應該有一個看起來像這樣的方法:
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