我在Entity Framework5中工作,在创建要在方法中使用的表达式时遇到问题。
我认为问题在于,通常我会在lambda表达式中调用表达式,例如dbContext.Counties.Select(GetLargeCities()),但在我使用的代码中,我将Counties实体投影到一个名为CountyWithCities的视图模型中。在我通常调用表达式的地方,我有一个单例c,但我不知道如何调用那里的表达式。
我希望使用表达式来完成此任务的原因是,我希望GetCountiesWithCities方法一次命中数据库,实体框架为结果中的所有对象构造一个复杂的图形。
由于某种原因,下面的代码会产生错误‘the name 'GetLargeCities’is is not in the current context.“
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);谢谢!
发布于 2013-10-17 12:51:24
我通常使用扩展方法来做这件事。
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
});
}https://stackoverflow.com/questions/19417982
复制相似问题