Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

c# - 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

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 when i try to run the application:

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType12[UnRelatedEntity.Models.t_AbortReason,UnRelatedEntity.Models.t_Activity]]', but this dictionary requires a model item of type 'UnRelatedEntity.Models.MobilePhoneXchangeEntities1'

I am using an Entity as a model which fetches Data from two tables seperately which do not have relation among them.

Controller:

public ActionResult Index()
{
    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 { Foo = foo, Bar = bar };
    return View(result);
}

View

@model UnRelatedEntity.Models.MobilePhoneXchangeEntities1

In the view I am just writing the above line i mean i am just inheriting the Model, nothing else but still I am confused about how to type cast model w.r.t model, but I am helpless.

Can anyone please provide me help on this, but please keep in mind i am using two unrelated tables in my model.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...