【问题标题】:Linq query to get filtred main collection and each list in result in that collectionLinq 查询以获取已过滤的主集合以及该集合中的每个列表
【发布时间】:2013-07-01 14:35:11
【问题描述】:

这些是我的课程:

public class Restaurant
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public City City { get; set; }
    public List<Meal> Meals { get; set; }
}

public class Meal
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public int Price { get; set; }
    public int Number { get; set; }
    public int Kind { get; set; }
}

现在我想创建一个查询,它为我提供城市餐厅列表以及今天日期的餐点列表,所以我开始这样:

return db.Restaurants.Where(rest => rest.City.Name == city).Include(rest => rest.Meals);

但我不确定如何与这部分连接:

.Where(meal => meal.Date == DateTime.Today)

所以我会得到我想要的结果。那么怎么可能做到这一点呢?谢谢

编辑:

我的结果:

        return db.Restaurants
                 .Include(rest => rest.Meals)
                 .Where(rest => rest.City.Name == city)
                 .AsEnumerable()
                 .Select(r => new Restaurant()
                     {
                         City = r.City,
                         Id = r.Id,
                         Name = r.Name,
                         Meals = r.Meals.Where(meal => meal.Date == DateTime.Today).ToList()
                     });

【问题讨论】:

    标签: c# linq collections ienumerable


    【解决方案1】:

    这应该在视图模型(或 Dto)层完成,首先,定义你的视图模型:

    public class RestaurantVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public City City { get; set; }
        public List<MealVM> Meals { get; set; }
    }
    
    public class MealVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }
        public int Price { get; set; }
        public int Number { get; set; }
        public int Kind { get; set; }
    }
    

    然后你可以像下面这样编写LINQ:

    var restaurantVMs = db.Restaurants
                      .Include(rest => rest.Meals)
                      .Where(rest => rest.City.Name == city)
                      .AsEnumerable()
                      .Select(r => new RestaurantVM(){
                            Id = r.Id,
                            Name = r.Name,
                            City = r.City,
                            Meals = r.Meals.Where(meal => meal.Date == DateTime.Today)
                                           .Select(m => new MealVM(){
                                                ...
                                            }).ToList()
                        }).Where(r => r.Meals.Count > 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多