I'm trying to dynamically build a LINQ query for LINQ to Entities so that I can avoid repeating the same function twice.
Here is what I'm trying to do:
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));
}
The filter
parameter is throwing this exception:
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities
I could potentially do this:
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));
}
But, that is not as clean.
Any suggestion?