【问题标题】:Excuting query: "LINQ to Entitites does not recognize method 'System.Object getItem(System.String)'"执行查询:“LINQ to Entities 无法识别方法‘System.Object getItem(System.String)’”
【发布时间】:2016-04-18 16:51:47
【问题描述】:

首先,我有这些模型:

我在控制器中得到了这个查询,我想把查询结果放到视图模型中:

var query = (from d in db.ObjectCategories
                    join a in db.MatchingObjects on d.Id equals a.ObjectCategoryId into grp3                        
                    join b in db.Unlocks
                        on d.Id equals b.ObjectCategoryId into grp1
                    from m in grp1.DefaultIfEmpty()
                    join c in db.Members
                        on m.StudentId equals c.Id into grp2
                    from n in grp2.DefaultIfEmpty()
                    where m.ObjectCategoryId == null
                    && n.Id == null
                    && n.Id == (int)Session["UserId"]
                    orderby d.Id
                    select new LockedCatListViewModel()
                    {
                        AnimalCategory = d.CategoryName,
                        AnimalCategoryId = d.Id,
                        Animals = d.MatchingObjects
                    }).AsEnumerable()
                     .Select(x=> new LockedCatListViewModel()
                    {
                        AnimalCategory = x.AnimalCategory,
                        AnimalCategoryId = x.AnimalCategoryId,
                        Animals = x.Animals
                    });
        return View(query.ToList());

视图模型:

public class LockedCatListViewModel
{
    [Display(Name = "Animal Category Name")]
    public string AnimalCategory { get; set; }
    public int AnimalCategoryId { get; set; }
    public virtual ICollection<MatchingObject> Animals { get; set; }
}

但是,每当我想在视图页面中的模型中循环项目,或者只是将此模型返回到视图页面时,我都会收到以下错误:

我尝试了许多不同的方法,我想知道在我的 LINQ 查询中应该做些什么才能得到我的 LINQ 查询的结果?

通过将 Session 赋值给一个变量来解决问题,并将该变量放入 Linq 中。

我认为这部分的 LINQ 查询不正确

 && n.Id == null
 && n.Id == (int)Session["UserId"]

【问题讨论】:

    标签: c# asp.net-mvc linq


    【解决方案1】:

    似乎有很多问题。首先,错误很可能是由于在您的 linq 中调用了Session。

    所以为了解决这个问题,将会话调用移到 linq 语句之外并分配给一个变量。

    int userId = (int)Session["userId"];
    

    然后您可以使用userId 变量代替会话调用。

    我认为您在此之后仍然会发现您的查询有问题,因为这些行:

    && n.Id == null
    && n.Id == (int)Session["UserId"] //or userId when you change it
    

    n.Id 怎么可能是 null 和一个值?

    【讨论】:

    • 嗨,Ashley Medway 感谢您的回复,它就像一个魅力。
    • 没问题,你会发现每当你需要调用一个方法时,它都需要在Linq之外完成,而Session["foo"]确实是一个方法调用。
    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多