ASP.NET MVC System.NotSupportedException LINQ to Entities qu

本文关键字:to Entities qu LINQ NotSupportedException NET MVC System ASP | 更新日期: 2023-09-27 18:25:44

我写了一个查询,如下所示:

var model = (from r in _db.Restaurants
     join rev in _db.Reviews
     on r.Id equals rev.RestaurantId
     into rest_rev
     from rr in rest_rev.DefaultIfEmpty()
     select new RestaurantViewModel
     {
        Id=r.Id,
        Name=r.Name,
        City=r.City,
        Country=r.Country,
        NumberofReviews=r.Reviews.Count,
        Reviews=rr.Body
     });

在进行一些更改之前,这个查询运行良好,然后我进行了一些更改(我不记得了),然后它开始发出这个错误图像

我的实体如下

public class Restaurant
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public virtual ICollection<RestaurantReview> Reviews { get; set; }
}
public class RestaurantReview
{
    public int Id { get; set; }
    public int Rating { get; set; }
    public string ReviewerName { get; set; }
    public string Body { get; set; }
    public int RestaurantId { get; set; }
}
public class RestaurantViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public int NumberofReviews { get; set; }
    public string Reviews { get; set; }    
}

ASP.NET MVC System.NotSupportedException LINQ to Entities qu

你可以试试这个。。。

List<RestaurantViewModel> listViewModel = new List<RestaurantViewModel>();
var model =  _db.Restaurants.Include("Reviews").ToList().ForEach((item) =>
            {
                RestaurantViewModel viewmodel = new RestaurantViewModel();
               viewmodel.ID = item.ID
               viewmodel.NumberofReviews = item.Reviews.Count;
               ....
                listViewModel.Add(viewmodel);
            });