实体框架asp.net mvc5-无法将lambda表达式转换为类型'string',因为它不是委托类型

问题描述 投票:0回答:1

我想做

IList<Sth> sths= Context.Sth.Where(g => g.IsX == true && g.Y.Name== "name").ToList();  //here it successfully compares  g.Y.Name
            foreach (Sth g in sths)
            {
                Context.Entry(g).Collection(g=>g.Y).Load(); //the exception is thrown here
                this.mylist.Add(g.Y.Id);
            }

我已经试过了

using System.Data.Entity;
using System.Linq;

.

c# asp.net-mvc entity-framework database-connection
1个回答
2
投票

g.Yis不是一个集合,否则你将无法在第一行调用g.Y.Name。所以你应该使用Reference而不是收集,或者最好使用Include代替。例如:

IList<Sth> sths = Context.Sth
    .Where(g => g.IsX == true && g.Y.Name== "name")
    .Include(g => g.Y)
    .ToList(); 

this.mylist.AddRange(sths.Select(g => g.Y.Id);

但是,如果你想要做的只是获得Id属性,那么你可以这样做:

this.mylist.AddRange(Context.Sth
    .Where(g => g.IsX == true && g.Y.Name== "name")
    .Select(g => g.Y.Id));
© www.soinside.com 2019 - 2024. All rights reserved.