我在使用 MVC 进行联接查询时遇到问题,但我不知道为什么。
无法在 LINQ to Entities 查询中构造实体或复杂类型“Tusofona_Website.Models.site_noticias”。
我的控制器:
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);
}
我的型号:
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; }
}
有人可以帮助我吗?
您无法投影到映射实体上(请参阅this回答)。
但是,您可以执行以下操作:
1)选择匿名类型而不是实体,例如:
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) 反转查询以直接选择 site_noticias。这取决于查询和您想要检索的数据。例如,您可以查看以下内容是否有效并为您提供所需的数据:
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) 使用一些 DTO(数据传输对象)将要选择的属性投影到:
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)