I been stuck in a situation and I tried finding the solution for it on net but was not successful. I am new to MVC with Entity Framework, and it is throwing the exception wh
None of the answers worked for me, but in the end, for some reason, EF 6 seemed to interpret this as a query:
var patient = db.Patient.Where(p => p.ID == id);
while this returned the Model I needed and works for me:
var patient = db.Patient.Where(p => p.ID == id).FirstOrDefault();
As Shad points out, the reason you are getting this error is simply because you are passing a different type of data into the view than what you have said you would.
To solve this, you need a model that you can pass into your view that holds the data you need:
public class FooBarModel
{
public AbortReason Foo { get;set;}
public Activity Bar { get;set;}
}
Then, in your Index
method, do something like this:
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);
}
And in your view, set the model type:
@model IEnumerable<my.namespace.FooBarModel>
The model item passed into the dictionary is of type 'Person.Models.Location', but this dictionary requires a model item of type 'Person.Models.LoginModel'.
Your view expects model of type UnRelatedEntity.Models.MobilePhoneXchangeEntities1
, but you pass result
object to it. result
is a database query, which you have described in controller action. So, you get expected error - type mismatch.
To fix this you should create type for your query items. Very simple example:
public class ResultItem
{
public Foo Foo { get; set; }
public Bar Bar { get; set; }
}
After that modify select statement in your query:
select new ResultItem { Foo = foo, Bar = bar };
and in the end, change model type of the view to IEnumerable<ResultItem>
, because query will return collection of result items.
Add a new object or instance with the correct type
@Html.Partial("_LoginPartial", new MVCTest.Models.LoginViewModel())