我正在使用Entity Framework 5,并且在创建要在方法中使用的表达式时遇到问题。
我认为问题在于通常我会在lambda表达式中调用表达式,例如dbContext.Counties.Select(GetLargeCities())
,但在我正在使用的代码中,我将Counties实体投影到名为CountyWithCities的视图模型中。在我通常称之为表达式的地方,我有一个单例c
,并且不知道如何在那里调用表达式。
我想使用表达式实现此目的的原因是因为我希望GetCountiesWithCities
方法命中数据库一次,实体框架为结果中的所有对象构建一个复杂的图形。
由于某种原因,下面的代码产生错误`当前上下文中不存在名称'GetLargeCities'。“
public class CountyWithCities // this is a view model
{
public int CountyID { get; set; }
public string CountyName { get; set; }
public IEnumerable<City> Cities { get; set; }
}
public class City // this is an entity
{
public int CityID { get; set; }
public string CityName { get; set; }
public int Population { get; set; }
}
public IEnumerable<CountyWithCities> GetCountiesWithCities(int StateID)
{
return dbContext.States
.Where(s => s.StateID = StateID)
.Select(s => s.Counties)
.Select(c => new CountyWithCities
{
CountyID = c.CountyID,
CountyName = c.CountyName,
Cities = GetLargeCities(c) // How do I call the expression here?
});
}
public Expression<Func<County, IEnumerable<City>>> GetLargeCities = county =>
county.Cities.Where(city => city.Population > 50000);
谢谢!
答案 0 :(得分:1)
我通常使用扩展方法执行此操作。
public static IQueriable<City> LargeCities(this IQueriable<County> counties){
return counties
.SelectMany(county=>county.Cities.Where(c=>c.Population > 50000));
}
用法:
dbContext.Counties.LargeCities()
public IEnumerable<CountyWithCities> GetCountiesWithCities(int StateID)
{
return dbContext.States
.Where(s => s.StateID = StateID)
.Select(s => s.Counties)
.LargeCities()
.GroupBy(c=>c.County)
.Select(c => new CountyWithCities
{
CountyID = g.Key.CountyID,
CountyName = g.Key.CountyName,
Cities = g.AsQueriable() // i cant remember the exact syntax here but you need the list from the group
});
}