传递实体框架查询以查看错误

时间:2014-08-08 15:09:27

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 localdb

我刚刚使用Entity Framework Code第一种方法创建了一个数据库。

这是我的模态类

public class MobileProduct
{
    [Key]
    public int p_id { get; set; }
    public string  p_name { get; set; }
    public string  p_description { get; set; }

    public string p_price { get; set; }
}

这是我的 DbContext 派生类

public class Entities : DbContext
{
   public DbSet<MobileProduct> Mobiles { get; set; }
}

我刚创建了一个查询,以便在动作方法

上传递此数据视图
Entities db = new Entities();
public ActionResult Mobiles()
{
    var q = from n in db.Mobiles
            select n;
    return View(q);
}

这是我的查看

@model HomeShopping.Models.MobileProduct

@{
    ViewBag.Title = "Mobiles";
}

<h2>Mobiles</h2>

访问视图时出现错误

  

传递到字典中的模型项的类型是&#39; System.Data.Entity.Infrastructure.DbQuery`1 [HomeShopping.Models.MobileProduct]&#39;,但是这个字典需要一个类型为&的模型项#39; HomeShopping.Models.MobileProduct&#39;

     

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

     

异常详细信息:System.InvalidOperationException:传递到字典中的模型项的类型为&#39; System.Data.Entity.Infrastructure.DbQuery`1 [HomeShopping.Models.MobileProduct]&#39;,但是这个字典需要一个类型为&#39; HomeShopping.Models.MobileProduct&#39;的模型项目。

4 个答案:

答案 0 :(得分:4)

我认为您想要向视图发送MobileProduct列表?如果是这样;将模型更改为

@model IEnumerable<HomeShopping.Models.MobileProduct>

@{
    ViewBag.Title = "Mobiles";
}

<h2>Mobiles</h2>

目前,您的模型只需要一个类型为MobileProduct的实例,而您的Mobiles操作则会创建一个MobileProduct列表。您还需要通过对其执行ToList()来评估操作中的查询。

public ActionResult Mobiles()
        {
            var q = from n in db.Mobiles
                    select n;
            return View(q.ToList());
        }

答案 1 :(得分:2)

您没有意识到您的查询,因此您将查询本身而不是查询结果发送到视图。

var q = (from n in db.Mobiles
         select n).ToList();
return View(q);

正如daveL发布的那样,您还需要在视图中更改模型的定义。

@model IEnumerable<HomeShopping.Models.MobileProduct>

答案 2 :(得分:0)

Haven未经过测试,但尝试将您的模型定义为:

@model IQuerable<HomeShopping.Models.MobileProduct>

如果这不起作用,那么可能:

@model IEnunerable<HomeShopping.Models.MobileProduct>

...将您的对象返回为:

View(q.ToList());

答案 3 :(得分:-1)

您要将查询保存到q,而不是查询的评估。如果您期望多个结果,则需要ToList()。

相关问题