尝试加载视图时出现此错误消息:
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType0`2[System.Int32,System.String]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[HelloWorld.Models.P]'.
可能是因为没有将正确的类型从Controller传递给View吗?
以下是模型:
public class P
{
[Key]
public virtual int ImportID { set; get; }
public virtual string MicroName { set; get; }
}
这是DBContext定义:
public DbSet<P> Ps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//REMAPPING TABLE NAMES
modelBuilder.Entity<P>()
.ToTable("SomeTable_With_Really_LongName_tbl");
base.OnModelCreating(modelBuilder);
}
这是Controller的行动:
public ActionResult ListP()
{
var model = (from p in _db.Ps
select new
{
p.ImportID,
p.MicroName
}).Take(10);
return View(model);
}
以下是观点:
@model IEnumerable<HelloWorld.Models.P>
@{
ViewBag.Title = "List P";
}
<h2>List P</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ImportID
</th>
<th>
MicroName
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImportID)
</td>
<td>
@Html.DisplayFor(modelItem => item.MicroName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
有什么想法吗?
答案 0 :(得分:1)
认为
var model = (from p in _db.Ps
select new
{
p.ImportID,
p.MicroName
}).Take(10);
返回导入ID和名称,它应返回P
的枚举数var model = _db.Ps.OrderBy(f => f.[FieldName]).Take(10);
答案 1 :(得分:0)
您收到此异常是因为View期望类型为IEnumerable<HelloWorld.Models.P>
的模型,但您传递的是一个匿名类型集合的模型。
在控制器中试试这个:
public ActionResult ListP()
{
var model = (from p in _db.Ps
select p).Take(10);
return View(model);
}
OR
public ActionResult ListP()
{
var model = (from p in _db.Ps
select new P
{
ImportID = p.ImportID,
MicroName = p.MicroName
}).Take(10);
return View(model);
}