簡體   English   中英

Linq查詢以獲取過濾后的主集合以及該集合中結果的每個列表

[英]Linq query to get filtred main collection and each list in result in that collection

這些是我的課程:

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()
                     });

這應該在視圖模型(或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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM