I have the following class
public class Account
{
IEnumerable<AccountData> Data { get; set; }
}
where AccountData is
public class AccountData
{
public virtual long Id { get; set; }
public virtual AccountTag AccountTag { get; set; }
public virtual string Value { get; set; }
}
and where Account Tag is
public class AccountTag
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
}
I want to return all accounts where the Data field is in a list of key value pairs . long is the AccountTag.Id, and the AccountData.Value contains the string
Here is what I have so far, but this is performed on the web server and there could be thousands of accounts returned so I am looking for a linq to sql version.
public IEnumerable<Account> FindByCompanyDataTags(long companyId, IEnumerable<KeyValuePair<long, string>> tags)
{
var tempAccounts = (from acc in this.Data where acc.Company.Id == companyId orderby acc.Name select acc);
IList<Account> accounts = new List<Account>();
foreach (var account in tempAccounts)
{
var matches = true;
foreach (var t in tags)
{
if (account.Data.Any(x => x.AccountTag.Id == t.Key && x.Value.Contains(t.Value)))
{
continue;
}
matches = false;
break;
}
if (matches)
{
accounts.Add(account);
}
}
return accounts;
}
If I use resharper to convert this into a linq expression I get the following
public IEnumerable<Account> FindByCompanyDataTags(long companyId, IEnumerable<KeyValuePair<long, string>> tags)
{
var tempAccounts = (from acc in this.Data where acc.Company.Id == companyId orderby acc.Name select acc);
IList<Account> accounts = (from account in tempAccounts let matches = tags.All(t => account.Data.Any(x => x.AccountTag.Id == t.Key && x.Value.Contains(t.Value))) where matches select account).ToList();
return accounts;
}
But when I run this I get a method not supported exception.
This is really confusing me, any suggestions?
That’s happening because in first case you prepare query to db during
foreachexecution hereYou get collection of
Accountobjects and working with them on client side in memory (other words, you’re using Linq to objects)In the second case you’re trying execute Linq to Sql query but provider cannot translate working with your
KeyValuePairobjects into sql query, therefore it raise exception said about that.UPDATE
Try to use
IQueryableand build your query thorugh consequently applyingWhereclause: