The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery', but this dictionary requires a model item of type B

前端 未结 5 1542
太阳男子
太阳男子 2020-12-18 13:16

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

相关标签:
5条回答
  • 2020-12-18 13:46

    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();
    
    0 讨论(0)
  • 2020-12-18 13:47

    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>
    
    0 讨论(0)
  • 2020-12-18 13:54

    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'.

    0 讨论(0)
  • 2020-12-18 14:03

    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.

    0 讨论(0)
  • 2020-12-18 14:05

    Add a new object or instance with the correct type

    @Html.Partial("_LoginPartial", new MVCTest.Models.LoginViewModel())

    0 讨论(0)
提交回复
热议问题