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;