Error: The entity or complex type cannot be constructed in a LINQ to Entities query

前端 未结 1 1367
南旧
南旧 2020-12-29 15:41

I have a problem with join query with MVC and i dont know why.

The entity or complex type \'Tusofona_Website.Models.site_noticias\' cannot be construc

相关标签:
1条回答
  • 2020-12-29 15:57

    You can't project onto a mapped entity (see this answer).

    However, you can do a couple of things:

    1) Select an anonymous type instead of entity like:

    var query = (from sd in db.site_desquesnoticias
                        join sn in db.site_noticias on sd.IDNoticia equals sn.IDNoticia
                        where sn.Destaque == 1
                        select new {
                            CorpoNoticia = sn.CorpoNoticia,
                            TituloNoticia = sn.TituloNoticia
                        }).ToList();
    

    2) Invert your query to select the site_noticias directly. That depends on the query and the data that you would like to retrieve. For example, you can have a look if the following will work and give you the data that you need:

    var query = (from sd in db.site_desquesnoticias
                        join sn in db.site_noticias on sd.IDNoticia equals sn.IDNoticia
                        where sn.Destaque == 1
                        select sn).ToList();
    

    3) Use some DTO (Data transfer object) to project the properties that you want to select on to:

       public class SiteNoticiasDTO{
         public string CorpoNoticia {get;set;}
         public string TituloNoticia {get;set;}
        }
    
    var query = (from sd in db.site_desquesnoticias
                        join sn in db.site_noticias on sd.IDNoticia equals sn.IDNoticia
                        where sn.Destaque == 1
                        select new SiteNoticiasDTO {
                            CorpoNoticia = sn.CorpoNoticia,
                            TituloNoticia = sn.TituloNoticia
                        }).ToList();
    
    0 讨论(0)
提交回复
热议问题