Error: object or complex type cannot be constructed in LINQ to Entities query

I have a problem requesting a connection to MVC and I don’t know why.

The object or complex type "Tusofona_Website.Models.site_noticias" cannot be constructed in a LINQ to Entities query.

My controller:

private TusofonaDBs db = new TusofonaDBs(); // // GET: /DestaquesMain/ public ActionResult Index() { 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 site_noticias { CorpoNoticia = sn.CorpoNoticia, TituloNoticia = sn.TituloNoticia }).ToList(); //return View(db.site_desquesnoticias.ToList()); return View(query); } 

My model:

 public class site_destaquesnoticias { [Key] public Int32 IDDestaque { get; set; } public Int32 IDNoticia { get; set; } public string Foto { get; set; } } public class site_noticias { [Key] public Int32 IDNoticia { get; set; } public string CorpoNoticia { get; set; } public string TituloNoticia { get; set; } public string Foto { get; set; } public Int32 Destaque { get; set; } } public class TusofonaDBs : DbContext { public DbSet<site_destaquesnoticias> site_desquesnoticias { get; set; } public DbSet<site_noticias> site_noticias { get; set; } } 

Can anybody help me?

+6
source share
1 answer

You cannot project onto a mapped entity (see this answer).

However, you can do a couple of things:

1) Choose an anonymous type instead of an object 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 directly select site_noticias. It depends on the request and the data you want to receive. For example, you can see if the following actions will be performed and provide the data 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 for which you want to select:

  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(); 
+14
source

Source: https://habr.com/ru/post/947286/


All Articles