我有一堆
Linq to Entity方法具有相同的select语句,所以我认为我会聪明并将其分离到它自己的方法来减少冗余……但是当我试图运行代码时,我得到了以下内容错误…
this method cannot be translated into
a store expression
这是我创建的方法……
public User GetUser(DbUser user,long uid) { return new User { Uid = user.uid,FirstName = user.first_name,LastName = user.last_name }; }
我打电话给这样的方法……
public User GetUser(long uid) { using (var entities = new myEntities()) { return entities.DbUsers.Where( x => x.uid == uid && x.account_status == ( short )AccountStatus.Active ). Select( x => GetUser( x,uid ) ).FirstOrDefault( ); } }
更新:这是内联工作的代码
public User GetUser(long uid,long uid_user) { using (var entities = new myEntities()) { var q = from u in entities.DbUsers where u.uid == uid_user select new User { Uid = u.uid,FirstName = u.first_name,LastName = u.last_name,BigPicUrl = u.pic_big,Birthday = u.birthday,SmallPicUrl = u.pic_small,SquarePicUrl = u.pic_square,Locale = u.locale.Trim(),IsFavorite = u.FavoriteFriends1.Any(x => x.uid == uid),FavoriteFriendCount = u.FavoriteFriends.Count,LastWishlistUpdate = u.WishListItems.OrderByDescending(x => x.added).FirstOrDefault().added,Sex = (UserSex)u.sex }; var user = q.FirstOrDefault(); user.DaysUntilBirthday = user.Birthday.DaysUntilBirthday(); return user; } }
解决方法
错误是现场,您无法将其转换为T-sql(或P-sql)查询.
保持简单,使用扩展方法.这就是他们的目的.
public static User ToUserEntity(this DbUser user) { return new User { Uid = user.uid,LastName = user.last_name }; }
然后在你的DAL中:
public User GetUser(long uid) { User dbUser; using (var entities = new myEntities()) { dbUser = entities.DbUsers .Where( x => x.uid == uid && x.account_status == (short)AccountStatus.Active ) .FirstOrDefault(); // query executed against DB } return dbUser.ToUserEntity(); }
在上下文处理后,看看我如何将POCO水合成一个物体?这样,在尝试水合成自定义对象之前,确保EF已完成表达式工作.
此外,我不知道为什么你将uid传递给那个方法,它甚至没有被使用.
再进一步说明,你不应该做这种事情(将EF POCO投射到你自己的对象中).