2016-06-09 52 views
1

我有從實體框架數據庫調用DbSet的方法:實體框架 - 如何將包含關閉傳遞給方法調用者?

public static List<CostEntryVM> ToViewModelList(this DbSet<CostEntry> CostEntrys, Expression<Func<CostEntry, bool>> query) { 

     return AutoMapper.Mapper.Map<List<CostEntry>, List<CostEntryVM>>(
       CostEntrys 
       .Include(x => x.Job) 
       .Include(x => x.User) 
       .Where(query) 
       .ToList()); 
    } 

要使用這個然後我就可以,例如做:

CostEntrys.ToViewModelList(x => x.Active == true); 

我也想能夠調用:

 CostEntrys.ToViewModelList(x => x.Include(y => y.Job).Include(y.User), x => x.Active == true); 

我不能爲我的生活找出方法簽名應該看起來如何,或者我會如何將它應用於DbSet。

我該怎麼做?

回答

1

首先,你需要更改擴展方法:

public static List<CostEntryVM> ToViewModelList(
     this DbSet<CostEntry> CostEntrys, 
     Expression<Func<CostEntry, bool>> query, 
     Func<IQueryable<CostEntry>, IQueryable<CostEntry>> func) 
{ 
    // Adding the predicate query 
    IQueryable<CostEntry> queryable = CostEntrys.Where(query); 

    // Adding include paths 
    IQueryable<CostEntry> queryableWithFetch = func(queryable); 

    // Executing the query and map it to the view model object 
    return AutoMapper.Mapper.Map<List<CostEntry>, List<CostEntryVM>>(
      queryableWithFetch.ToList()); 
} 

然後你就可以把它叫做:

CostEntrys.ToViewModelList(
     x => x.Active == true, 
     x => x.Include(y => y.Job).Include(y.User));