Local sequence cannot be used in LINQ to SQL
10.06.2008 Вторник 21:10
Gor the following exception with LINQ:
System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator
The LINQ query looked like this:
public static Service[] GetByGuids(Guid[] guids)
{
var q =
from s in Context.Services
join g in guids on s.ID = g
select s;
return q.ToArray();
}
The reason for the error is that guids is an in-memory array. When using with LINQ to SQL such arrays would need to be translated to SQL somehow, which is not supported by current LINQ to SQL implementation. The work around is:
public static Service[] GetByGuids(Guid[] guids) {
Service[] services = null;
foreach (Guid g in guids) {
Service[] s1 =
(from s in Context.Services
where s.ID == g
select s).ToArray();
if (services == null) {
services = s1;
} else {
services = services.Union(s1).ToArray();
}
}
return services;
}
Go figure! :)
UPDATE 6/12/08It turned out the above logic can be implemented in a much easier way with use of "Contains":
public static Service[] GetByGuids(Guid[] guids) {
var q =
from s in Context.Services
where guids.Contains(s.ID)
select s;
return q.ToArray();
}