asp.net MVC 在列表中的位置
本文关键字:位置 列表 net MVC asp | 更新日期: 2023-09-27 18:33:50
我用 c# 和 sp.net MVC 5 构建我的第一个应用程序,到目前为止:)
现在我有一个问题,我们使用 2 个用户表,第一个包含用户名,另一个包含用户数据。
string user = User.Identity.Name;
var data = db.FE_Benutzer;
var collection = data.Where(o => o.Benutzername == user).Select(x => new
{
id = x.ID,
name = x.Name,
hauptbereiche = x.Hauptbereich.ToList()
});
var dataHauptbereich = db.Hauptbereich;
var collectionHauptbereich = dataHauptbereich.Where(o => collection.ElementAt(0).hauptbereiche.Contains(o)).Select(x => new
{
id = x.ID,
name = x.Name
});
return Json(collectionHauptbereich, JsonRequestBehavior.AllowGet);
我收到此错误
LINQ to Entities 无法识别方法 '<>f__AnonymousType6
3[System.Int32,System.String,System.Collections.Generic.List
1[灼热.Models.Hauptbereich]] ElementAt[<>f__AnonymousType63](System.Linq.IQueryable
1[<>f__AnonymousType63[System.Int32,System.String,System.Collections.Generic.List
1[scorring.Models.Hauptbereich]]]、Int32(' 方法,并且此方法不能转换为存储表达式。
hauptbereiche = x.Hauptbereich.ToList((
包含用户有权访问的 ID 列表。
当我获取数据时
dataHauptbereich.Where
我不会只包含我在列表中拥有的 ID
这怎么可能?
实体框架不知道如何将ElementAt
转换为SQL。有关详细信息,请参阅此答案:从 LINQ 查询获取第一个结果 - 为什么 ElementAt
尝试
dataHauptbereich.Where(o => collection.ElementAt(0).hauptbereiche.Any(h => h.ID == o.ID))
或
dataHauptbereich.Where(o => collection.Any(c => c.hauptbereiche.Any(h => h.ID == o.ID)))
我花了一些时间来破译您在这里使用代码实现的目标,但在我看来,您只是简单地查询属于特定用户的Hauptbereich
。你的第一个查询选择一个由id
、name
和hauptbereiche
组成的匿名对象,但你只使用hauptbereiche
属性。然后,在第二个查询中,只需选择与此hauptbereiche
属性集合中的项匹配的Hauptbereich
。实际上,在这里,您只是比较原始集合中第一项的值,这就引出了一个问题,即为什么要选择第一项以外的任何内容。第二个查询完全是多余的,因为如果项目匹配,则意味着您首先已经拥有了这些项目。您可以直接从collection.ElementAt(0).hauptbereiche
获取相同的信息,而无需发出第二个查询。
因此,这里有几个更简单的选项:
-
如果您试图获取属于所有
FE_Benutzer
的所有Hauptbereich
Benutzername == user
那么只需执行以下操作:var collectionHauptbereich = db.FE_Benutzer.Where(m => m.Benutzername == user) .Include(m => m.Hauptbereich) .SelectMany(m => m.Hauptbereich);
-
如果您只想要第一个
FE_Benutzer
项的Hauptbereich
,请执行以下操作:var benutzer = db.FE_Benutzer.Where(m => m.Benutzername == user) .Include(m => m.Hauptbereich) .FirstOrDefault(); var collectionHauptbereich = benutzer != null ? benutzer.Hauptbereich.ToList() : new List<Hauptbereich>();