We are using .NET Entity Framework in our project and today I wrote a LINQ to Entities query to fetch records from table A if corresponding records are not found in table B. Let us take example of customer orders scenario. I want to get all the customers who don't have a order in the Orders table. What I needed was "NOT IN" or "NOT EXISTS" SQL equivalent in LINQ to Entities. I knew that we have Contains() method in LINQ to SQL which is equivalent to NOT EXISTS in SQL. So, I tried following LINQ to Entities query to return all the costumers who don't have a order in the Orders table:
from c in context.Customers
where !( from o in context.Orders select o.CustomerId ).Contains( c.CustomerId )
select c
I was confident this would work, but no the above query did not work!!. I got an error that LINQ to Entities does not support Contains() method. It is frustrating to know that the same Contains() method works in LINQ to SQL but not in LINQ to Entities. Why not support such basic functionality.
I had other frustrating moments with LINQ to Entities too. I prefer to just use LINQ to SQL and stay away from LINQ to Entities.
No comments:
Post a Comment