Asp.net mvc 查找集合中包含的实体时出现实体框架查询异常
我正在运行下面的查询,以获取我在特定日期参加的所有活动(作为注册学生),并得到一个错误,即 System.NotSupportedException:无法创建“YogaBandy.Models.Profile.YogaProfile”类型的常量值。在此上下文中仅支持基元类型或枚举类型 下面是我用来获取我在特定日期注册的所有事件的查询Asp.net mvc 查找集合中包含的实体时出现实体框架查询异常,asp.net-mvc,entity-framework,linq,Asp.net Mvc,Entity Framework,Linq,我正在运行下面的查询,以获取我在特定日期参加的所有活动(作为注册学生),并得到一个错误,即 System.NotSupportedException:无法创建“YogaBandy.Models.Profile.YogaProfile”类型的常量值。在此上下文中仅支持基元类型或枚举类型 下面是我用来获取我在特定日期注册的所有事件的查询 // my profile var yogaProfile = dbContext.YogaProfiles.Where(i => i.Application
// my profile
var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();
// events I'm registered for on a specific day
var eventsNew = dbContext.YogaSpaceEvents.Where(
i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active
&& i.RegisteredStudentsNew.Contains(yogaProfile)).ToList();
我想这可能和角色有关,但不确定
&&i.注册学生新含(酸奶配方)
仅供参考-我的RegisteredStudentsNew在“YogaSpaceEvents”实体中看起来像这样
public virtual ICollection<YogaProfile> RegisteredStudentsNew { get; set; }
尝试将
yogaprofile.Where(i=>i.applicationserid==userId)
移动到Include
语句中
示例:
var eventsNew = dbContext.YogaSpaceEvents
.Include(p=>p.RegisteredStudentsNew.Where(rp => rp.ApplicationUserId == userId))
.Where( i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active)
.ToList();
或
在where
子句中使用Any
var eventsNew = dbContext.YogaSpaceEvents
.Include(p=>p.RegisteredStudentsNew)
.Where(i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active
&& i.RegisteredStudentsNew.Any(rp => rp.ApplicationUserId == userId))
.ToList();
请阅读为什么在LINQ中使用
Include
。i.RegisteredStudentsNew.Contains(yogaProfile)
看起来可疑您不能在中使用复杂对象。Contains
那么我如何搜索我需要的?它似乎应该在Contains中接受yogaProfile,因为当我将鼠标悬停在.Contains方法上时,我会看到'Models.Profile.YogaProfile',这就是我传递给它的内容。我运行了第一个示例,但得到异常“System.ArgumentException:包含路径表达式必须引用在类型上定义的导航属性。使用虚线路径引用导航属性,使用Select运算符引用集合导航属性。参数名称:path”@user1186050您是两个都试还是第一个都试?请使用第二个。@user1186050请阅读此答案为什么不能使用第一个。Ashiquzzaman-我认为我向注册的学生新虚拟ICollection添加瑜珈饼文件的方式存在问题。我在YogaProfile表中添加“YogaSpaceEvent_YogaSpaceEventId”时创建的列只保存一个int值。因此,如果我添加一个配置文件,它会很好地保存它,例如1234,但是当我添加另一个配置文件时,它会用一个新值4567覆盖第一个值1234。因此,当我搜索时,根据您的请求,我将始终只收到1个返回的profile.FYI-这必须是一个YogaProfile的集合,因此registeredstudentsnew(复数),当我查看迁移文件时,它将列显示为int
var eventsNew = dbContext.YogaSpaceEvents
.Include(p=>p.RegisteredStudentsNew)
.Where(i => i.EventDateTime.Day == date.Day
&& i.EventStatus == YogaSpaceEventStatus.Active
&& i.RegisteredStudentsNew.Any(rp => rp.ApplicationUserId == userId))
.ToList();