Showing posts with label LINQ to Entities. Show all posts
Showing posts with label LINQ to Entities. Show all posts

Monday, August 8, 2011

Entity Framework Error: Resource not found for segment 'Property'

I was getting "Resource not found for segment 'Property'" error with the below code. I am loading some data from the database using .Net Entity Framework.


 private void LoadItem(int specId)
 {
       var query = DataContext.Items.Where( x => x.SpecId == specID );

       DataServiceQuery dsq = DataServiceQuery)query;

       dsq.BeginExecute(  ar =>
       {
             this.items = dsq.EndExecute( ar ).SingleOrDefault();
       },
       null );
       }
 }

The above code threw an exception when the data query returned no records. I was expecting SingleOrDefault() to return default value (which is NULL) if no matching records were found. But, instead I was getting "Resource not found for segment 'Property'" exception.

After doing some investigation I found out that the exception was due to the fact that I was using primary key field in my data service query.

       var query = DataContext.Items.Where( x => x.SpecId == specID );

Here the field SpecId was a primary key. In Entity Framework if your data service query is performed on a primary key, then SingleOrDefault() and FirstOrDefault() methods will throw an exception if no matching records were found.

To resolve this issue, I set the following property to TRUE on the data service DataContext. This line will suppress the "Resource Not Found" exception.

DataConext.IgnoreResourceNotFoundException = true;

Thursday, February 17, 2011

LINQ to Entities does not support Contains() method

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.