Convertire un tipo in un IEnumerable generico
Usare AsEnumerable per restituire l'argomento tipizzato come IEnumerable
generico.
Esempio
In questo esempio LINQ to SQL tenta di convertire la query in SQL e di eseguirla sul server usando il tipo Query
generico predefinito. La clausola where
, tuttavia, fa riferimento a un metodo sul lato client definito dall'utente (isValidProduct
) che non può essere convertito in SQL.
La soluzione consiste nello specificare l'implementazione di IEnumerable<T> del tipo where
generico sul lato client per sostituire il tipo IQueryable<T> generico. Per eseguire questa operazione, richiamare l'operatore AsEnumerable.
private bool isValidProduct(Product prod)
{
return prod.ProductName.LastIndexOf('C') == 0;
}
void ConvertToIEnumerable()
{
Northwnd db = new Northwnd(@"c:\test\northwnd.mdf");
Program pg = new Program();
var prodQuery =
from prod in db.Products.AsEnumerable()
where isValidProduct(prod)
select prod;
}
Private Function isValidProduct(ByVal prod As Product) As Boolean
Return prod.ProductName.LastIndexOf("C") = 0
End Function
Sub ConvertToIEnumerable()
Dim db As New Northwnd("c:\northwnd.mdf")
Dim validProdQuery = _
From prod In db.Products.AsEnumerable _
Where isValidProduct(prod) _
Select prod
End Sub