简体   繁体   中英

System.NotSupportedException : When I run this Linq query

The entity or complex type 'CategoryModel.ItemModel' cannot be constructed in a LINQ to Entities query.

var query1 = (from a in db.ItemModels
                              select new ItemModel
                              {
                                  Id = a.Id,
                                  Name = a.Name,
                                  Path = a.Path
                              }).ToList();

How can write this in another form?

A LINQ provider will not know what code is inside the MovieSummary constructor because the constructor code isn't captured in the expression tree generated by the query. The Entity Framework tries to translate everything in the LINQ query into T-SQL, but since it can't tell exactly what is happening inside the constructor call it has to stop and throw an exception.

One solution is to move the entire projection out of the expression tree by switching from IQueryable to IEnumerable (using the AsEnumerable LINQ operator).

var summaries = db.Movies.AsEnumerable()
                  .Select(m => new MovieSummary(m));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM