Reputation: 363
Got this error message while trying to load view:
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]'.
Could it be from not passing the correct type from the Controller to the View?
Here's the model:
public class P
{
[Key]
public virtual int ImportID { set; get; }
public virtual string MicroName { set; get; }
}
Here's the DBContext definition:
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);
}
Here's the Controller action:
public ActionResult ListP()
{
var model = (from p in _db.Ps
select new
{
p.ImportID,
p.MicroName
}).Take(10);
return View(model);
}
Here's the view:
@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>
Any ideas?
Upvotes: 0
Views: 3632
Reputation: 1935
think that
var model = (from p in _db.Ps
select new
{
p.ImportID,
p.MicroName
}).Take(10);
is returning the Import ID and Name where it should be returning a enumerator of P
var model = _db.Ps.OrderBy(f => f.[FieldName]).Take(10);
Upvotes: 1
Reputation: 997
You are getting this exception because the View is expecting a model of type IEnumerable<HelloWorld.Models.P>
, but you are passing it a model that is a collection of Anonymous Type.
In the controller try this:
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);
}
Upvotes: 0