System.NotSupportedException:无法在LINQ to Entities查询中构造实体或复杂类型“Resturant.Models.RestaurantViewModel” [英] System.NotSupportedException: The entity or complex type 'Resturant.Models.RestaurantViewModel' cannot be constructed in a LINQ to Entities query
本文介绍了System.NotSupportedException:无法在LINQ to Entities查询中构造实体或复杂类型“Resturant.Models.RestaurantViewModel”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个如下查询:
I have written a query which is as follows:
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
});
在进行一些更改之前,这个查询工作正常,然后我做了一些更改(我不记得了),然后开始发出此错误
错误图片
我的实体如下:
Before making some changes this query worked fine and then I made some changes (which I don't remember), then it started issuing this error
Error Image
My Entities are as follows:
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; }
}
请帮我解决这个错误。
谢谢
Please help me solve this error.
Thank you
推荐答案
EF不允许您将查询的复杂结果投影到映射的实体上。您可以使用不从映射实体继承的DTO或匿名类型。
尝试使用以下代码:
EF doesn't allow you to project the complex results of a query onto a mapped entity. You can do use a DTO or anonymous type which doesn't inherit from the mapped entity.
Try with below code:
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
{
Id=r.Id,
Name=r.Name,
City=r.City,
Country=r.Country,
NumberofReviews=r.Reviews.Count,
Reviews=rr.Body
}).ToList().Select(rec = > new RestaurantViewModel()
{
Id=rec.Id,
Name=rec.Name,
City=rec.City,
Country=rec.Country,
NumberofReviews=rec.Reviews.Count,
Reviews=rec.Body
});
这篇关于System.NotSupportedException:无法在LINQ to Entities查询中构造实体或复杂类型“Resturant.Models.RestaurantViewModel”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文