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 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; }
}
Anyone can help me?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With