gpt4 book ai didi

c# - 我可以在 LINQ to Entities 中动态构建 where 子句吗?

转载 作者:太空宇宙 更新时间:2023-11-03 11:45:16 25 4
gpt4 key购买 nike

我正在尝试为 LINQ to Entities 动态构建 LINQ 查询,这样我就可以避免重复相同的函数两次。

这是我正在尝试做的事情:

private IUser GetOrUpdateUser(Predicate<IUser> filter, Func<IIdentityProvider, UserRecord> fetch)
{
var user = (from u in this.adapter.Users
where filter(u)
select u).SingleOrDefault();

if (user == null)
{
// User not found. Add him.
user = this.adapter.AddUser(fetch(this.idenityProvider));
}
else if (user.IsExpired)
{
// User found, but expired. Update him.
this.adapter.UpdateUser(user, fetch(this.idenityProvider));
}

return user;
}

protected IUser GetUserByNetworkId(string username)
{
return GetOrUpdateUser(
u => u.NetworkId == username,
i => i.GetUserByNetworkId(username));
}

protected IUser GetUserByEmail(string email)
{
return GetOrUpdateUser(
u => u.Email == email,
i => i.GetUserByEmail(email));
}

filter 参数抛出此异常:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities

我可能会这样做:

protected IUser GetUserByNetworkId(string username)
{
return GetOrUpdateUser(
from u in this.adapter.Users
where u.NetworkId == username
select u,
i => i.GetUserByNetworkId(username));
}

protected IUser GetUserByEmail(string email)
{
return GetOrUpdateUser(
from u in this.adapter.Users
where u.Email == email
select u,
i => i.GetUserByEmail(email));
}

但是,那不是那么干净。

有什么建议吗?

最佳答案

您可以组合这两种 LINQ 语法:

private IQueryable<IUser> BuildQuery(IQueryable<IUser> users, string userName)
{
users = users.Where(u => u.UserName == userName);
return users;
}

然后当你调用它时:

var query = from u in this.BuildQuery(this.adapter.Users, userName)
select u;

希望这会为您指明正确的方向!

关于c# - 我可以在 LINQ to Entities 中动态构建 where 子句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3585342/

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