0

我在 Entity Framework 5 中工作,并且在创建要在方法中使用的表达式时遇到问题。

我认为问题在于通常我会在 lambda 表达式中调用该表达式dbContext.Counties.Select(GetLargeCities()),但在我正在使用的代码中,我将 Counties 实体投影到名为 CountyWithCities 的视图模型中。在我通常调用表达式的地方,我有一个单例c并且不知道如何在那里调用表达式。

我想使用表达式完成此操作的原因是因为我希望该GetCountiesWithCities方法访问数据库一次,而 Entity Framework 为结果中的所有对象构造一个复杂的图形。

出于某种原因,下面的代码会产生错误“当前上下文中不存在名称‘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);

谢谢!

4

1 回答 1

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
            });
    }
于 2013-10-17T04:51:24.163 回答