【问题标题】:EF code first cannot convert type to intEF 代码首先无法将类型转换为 int
【发布时间】:2014-03-05 09:53:56
【问题描述】:

我正在我的餐厅评论网站上创建一个函数,该函数获取上次评论的菜式,然后查找具有相同菜式且平均得分较高的其他评论。然后它将每个餐厅 ID 保存在数据库中。但是,我继续在where r.id = samecuisine 线上收到错误Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int'

任何帮助将不胜感激。

var samecuisine = (from r in db.Reviews
                   where r.Cuisine == review.Cuisine
                   select r.id);

var pick = (from r in db.Reviews
            where r.id = samecuisine
            select r.score).Average();

var choices = (from r in db.Reviews
               where r.score >= pick
               select r.RestaurantId).ToList();

【问题讨论】:

    标签: c# asp.net-mvc linq entity-framework ef-code-first


    【解决方案1】:

    目前还不清楚您为什么想要获得评论 ID。你只对那些评论的分数感兴趣,对吧?我怀疑您实际上想参与您的第一个查询和第二个查询的一部分:

    var averageScoreForCuisine = (from r in db.Reviews
                                  where r.Cuisine == review.Cuisine
                                  select r.score).Average();
    

    或者在我看来更具可读性:

    var averageScoreForCuisine = db.Reviews
                                   .Where(r => r.Cuisine == review.Cuisine)
                                   .Average(r => r.score);
    

    【讨论】:

      【解决方案2】:

      您的查询

      var samecuisine = (from r in db.Reviews
                         where r.Cuisine == review.Cuisine
                         select r.id);
      

      返回IQueryable<int>,而不是实际的int

      尝试检索.FirstOrDefault(),这会产生第一个结果(或默认值0)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多