I've read similar questions on SO but can't seem to figure out this issue, which is specific to DBContext objects (I think). Here's some dummy code to illustrate.
I have the following code in my Index() action:
public ActionResult Index()
{
AnimalDBContext db = new AnimalDBContext();
return View(db.Dogs);
}
I have the following code for my models:
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class AnimalDBContext : DbContext
{
public DbSet<Dog> Dogs { get; set; }
}
In my view I have the following:
@model IEnumerable<AnimalProject.Models.Dog>
@foreach (var d in Model)
{
<h3>@d.name</h3>
<h2>@d.breed</h2>
}
Everything works great, the view will loop through every dog in my database. However, I have another set of DBContext data from another table that I want in the same view. I want to be able to enumerate each item in the database for that table as well.
This is what I want, if you catch my drift:
@model IEnumerable<AnimalProject.Models.Dog>
@model IEnumerable<AnimalProject.Models.Cat>
@foreach (var d in Dog)
{
<h3>@d.name</h3>
<h2>@d.breed</h2>
}
@foreach (var c in Cat)
{
<h3>@c.name</h3>
<h2>@c.breed</h2>
}
I have tried grouping the classes together and using a partial view, but apparently you can't have a different model in a partial view, because I always get the error message:
"The model item passed into the dictionary is of type 'System.Data.Entity.DbSet
1[AnimalProject.Models.Dog]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1[AnimalProject.Models.Cat]'."
So, how can I use multiple models in my view that both get the data I want from separate tables in the database?