gpt4 book ai didi

c# - 是什么导致 Linq 错误 : This method cannot be translated into a store expression?

转载 作者:太空狗 更新时间:2023-10-29 21:07:05 25 4
gpt4 key购买 nike

我有一堆具有相同 select 语句的 Linq to Entity 方法,所以我认为我会很聪明,将其分离到它自己的方法中以减少冗余......但是当我尝试运行代码时,我出现以下错误...

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,
FirstName = user.first_name,
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 投影到您自己的对象中)。

如果您这样做,这是自定义 POCO 的一个很好的案例(将表直接映射到您的自定义 POCO,不要使用代码生成)。

关于c# - 是什么导致 Linq 错误 : This method cannot be translated into a store expression?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com