我陷入了困境,我尝试在网上找到解决方案,但没有成功。我是 MVC 与实体框架的新手,当我尝试运行应用程序时它抛出异常:
传入字典的模型项的类型为“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);
}
Run Code Online (Sandbox Code Playgroud)
看法
@model UnRelatedEntity.Models.MobilePhoneXchangeEntities1
Run Code Online (Sandbox Code Playgroud)
在视图中,我只是在写上面的行,我的意思是我只是继承了模型,没有别的,但我仍然对如何输入模型和模型的类型感到困惑,但我很无助。
任何人都可以为此提供帮助,但请记住,我在我的模型中使用了两个不相关的表。
正如 Shad 指出的那样,您收到此错误的原因仅仅是因为您向视图中传递的数据类型与您所说的不同。
为了解决这个问题,您需要一个模型,您可以将其传递到包含您需要的数据的视图中:
public class FooBarModel
{
public AbortReason Foo { get;set;}
public Activity Bar { get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后,在你的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);
}
Run Code Online (Sandbox Code Playgroud)
在您看来,设置模型类型:
@model IEnumerable<my.namespace.FooBarModel>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30348 次 |
最近记录: |