传递到字典中的模型项的类型为’System.Data.Entity.Infrastructure.DbQuery’,但此字典需要B类型的模型项
我一直陷入困境,我试图在网上找到它的解决方案,但没有成功。 我是使用Entity Framework的MVC的新手,当我尝试运行应用程序时抛出exception:
传递到字典中的模型项的类型为’System.Data.Entity.Infrastructure.DbQuery
1[f__AnonymousType1
2 [UnRelatedEntity.Models.t_AbortReason,UnRelatedEntity.Models.t_Activity]]’,但此字典需要模型项输入’UnRelatedEntity.Models.MobilePhoneXchangeEntities1′
我使用一个实体作为一个模型,它从两个表中分别获取数据,这两个表之间没有关系。
控制器:
public ActionResult Index() { MobilePhoneXchangeEntities1 ent = new MobilePhoneXchangeEntities1(); var result = from foo in ent.t_AbortReason from bar in ent.t_Activity where foo.AbortReasonCategoryId != null && bar.ActivityId != null select new { Foo = foo, Bar = bar }; return View(result); }
视图
@model UnRelatedEntity.Models.MobilePhoneXchangeEntities1
在视图中我只是写上面的行我的意思是我只是inheritance模型,没有其他但我仍然对如何键入演员模型wrt模型感到困惑,但我很无奈。
任何人都可以请我帮忙,但请记住我在我的模型中使用两个不相关的表。
正如Shad指出的那样,你得到这个错误的原因只是因为你将不同类型的数据传递给视图而不是你所说的。
要解决此问题,您需要一个可以传递到视图中的模型,该模型包含您需要的数据:
public class FooBarModel { public AbortReason Foo { get;set;} public Activity Bar { get;set;} }
然后,在您的Index
方法中,执行以下操作:
using(MobilePhoneXchangeEntities1 ent = new MobilePhoneXchangeEntities1()) { var result = from foo in ent.t_AbortReason from bar in ent.t_Activity where foo.AbortReasonCategoryId != null && bar.ActivityId != null select new FooBarModel() { Foo = foo, Bar = bar }; return View(result); }
在您的视图中,设置模型类型:
@model IEnumerable
没有一个答案对我有用,但最后,由于某些原因,EF 6似乎将此解释为一个查询:
var patient = db.Patient.Where(p => p.ID == id);
虽然这回归了我需要的模型并为我工作:
var patient = db.Patient.Where(p => p.ID == id).FirstOrDefault();
您的视图需要UnRelatedEntity.Models.MobilePhoneXchangeEntities1
类型的UnRelatedEntity.Models.MobilePhoneXchangeEntities1
,但您将result
对象传递给它。 result
是一个数据库查询,您已在控制器操作中对其进行了描述。 因此,您会得到预期的错误 – 类型不匹配。
要解决此问题,您应该为查询项创建类型。 很简单的例子:
public class ResultItem { public Foo Foo { get; set; } public Bar Bar { get; set; } }
之后修改查询中的select语句:
select new ResultItem { Foo = foo, Bar = bar };
最后,将视图的模型类型更改为IEnumerable
,因为查询将返回结果项的集合。
传递到字典中的模型项的类型为“Person.Models.Location”,但此字典需要“Person.Models.LoginModel”类型的模型项。
添加具有正确类型的新对象或实例
@ Html.Partial(“_ LoginPartial”,新的MVCTest.Models.LoginViewModel())