LINQ转SQL时遇异常:无法创建ApplicationUser类型常量值求解决
解决LINQ查询中的EF实体比较异常
这个异常的核心原因很明确:Entity Framework没办法把整个实体对象的比较(比如你写的GNA.UserName == user)转换成对应的SQL语句。EF只能处理原始类型(字符串、数字、枚举这类)的条件判断,不能直接对比ApplicationUser这样的复杂实体实例。
另外我注意到你的join条件还存在一个逻辑错误:你现在用GNS.id equals GNA.id关联,这是把GamesNight的主键和GamesNightAttendance自己的主键绑定,完全不符合业务逻辑——参与记录的主键和活动主键是完全独立的,正确的关联应该是通过GamesNightAttendance里的GameNight导航属性对应的外键。
下面是修正后的几种写法:
写法1:修正join和条件判断(用导航属性)
var userID = User.Identity.GetUserId(); var result = from GNS in db.GamesNights join GNA in db.GamesNightAttendance on GNS.id equals GNA.GameNight.Id // 修正关联:用活动的主键匹配参与记录关联的活动ID where GNS.Active && GNA.UserName.Id == userID // 用用户ID做判断,而非整个user对象 select new UpcomingGNAttendanceViewModel { GamesNight = GNS, Attendance = GNA.Attendance };
写法2:用显式外键(更高效)
如果你的GamesNightAttendance模型里显式声明了外键字段(比如GameNightId和UserId,这是EF的最佳实践),可以直接用外键做关联和判断,避免导航属性的额外开销:
var userID = User.Identity.GetUserId(); var result = from GNS in db.GamesNights join GNA in db.GamesNightAttendance on GNS.id equals GNA.GameNightId where GNS.Active && GNA.UserId == userID select new UpcomingGNAttendanceViewModel { GamesNight = GNS, Attendance = GNA.Attendance };
写法3:利用导航属性简化查询(无需显式join)
EF的导航属性可以帮你自动处理表关联,代码会更简洁:
var userID = User.Identity.GetUserId(); var result = db.GamesNightAttendance .Where(gna => gna.UserName.Id == userID && gna.GameNight.Active) .Select(gna => new UpcomingGNAttendanceViewModel { GamesNight = gna.GameNight, Attendance = gna.Attendance });
这些修改后,EF就能正确把LINQ转换成对应的SQL语句,不会再抛出那个实体比较的异常了。
内容的提问来源于stack exchange,提问作者Kilvery house
相关产品推荐
相关产品推荐

