0

These are my classes:

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

and now I want to create a query which give me list of restaurants in city with list of meals which has today date so I started like this:

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

But I am not sure how to connected with this part:

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

so I would get results which I want. So how is possible to do this? Thanks

Edit:

My result:

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

1 回答 1

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);
于 2013-07-01T14:54:16.107 回答