这些是我的课程:
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()
});
答案 0 :(得分:1)
这应该在View Model(或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);