将列表保存到数据库

时间:2014-03-05 10:45:55

标签: c# asp.net asp.net-mvc

我在我的餐厅评论网站上创建了一个功能,找到了上次评论的美食,然后找到了相同菜系的其他评论,平均得分更高,然后将这些评论的餐馆ID保存到数据库的表格中。但是我继续收到错误:

  

无法将方法组分配给隐式类型的局部变量。

restaurantid = choices行。任何帮助都会感激不尽。

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

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

foreach (var item in choices)
{
    var suggestion = new Suggestion()
    {
        id = review.id,
        Userid = review.UserId,
        restaurantid = choices
    };

    db.Suggestions.Add(suggestion);
    db.SaveChanges();
}

3 个答案:

答案 0 :(得分:3)

以下行:

var choices = (from ...).ToList;

应该是:

var choices = (from ...).ToList();

其次,我认为restaurantid的类型为int。使用您的代码,您将为{int}分配List<int>。这应该是item,来自循环。

答案 1 :(得分:0)

您需要进行以下更改:

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

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

foreach (var item in choices)
{
    var suggestion = new Suggestion()
    {
        id = review.id,
        Userid = review.UserId,
        restaurantid = item //here was your problem, you need to assign an id not a list of ids
    };

    db.Suggestions.Add(suggestion);
    db.SaveChanges();
}

答案 2 :(得分:0)

你试过这样的事吗:

var choices = (from r in db.Reviews
                    where r.score <= averagescore
                    select r).ToList;
    foreach (var item in choices)
            {
             var suggestion = new Suggestion()
                            {
                             id = item.id,
                             Userid = item.UserId,
                             restaurantid = item.Restaurantid
                             };
                             db.Suggestions.Add(suggestion);
                             db.SaveChanges();
            }