3

I have DataService where T is an EntityFramework DbContext class

My client app is a Windows Forms app with a Service Reference.

What is the best approach to get a single entity from the service?

This code works:

var uri = new Uri("http://localhost/ProductService.svc/");
var context = new ProductContext(uri);
var result = context.Products.Where(x => x.ProductId == 123).FirstOrDefault();

However, it works because the product exists. That is because I can see the result by executing

http://localhost/ProductService.svc/Products(123)

in the browser. If I want to query product 123456, which does not exist in the database

http://localhost/ProductService.svc/Products(123456)

I see an errortext ` Resource not found for the segment 'Products'

The thing is, on the client side I get an exception but I would expect FirstOrDefault() to be null instead. Sure I could use some exception handling, but I am wondering if my approach is correct or if there is a better way to fetch a single object.

Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189

1 Answers1

3

Update: Found the solution here https://stackoverflow.com/a/5987733/98491

The key is to set

context.IgnoreResourceNotFoundException = true;

Now SingleOrDefault() and FirstOrDefault() behave like I would expect. But I am still wondering if this is the right decision because in a browser

 http://localhost/ProductService.svc/Prodducts(1)

(notice the typo) throws the same ResourceNotFound exception

Community
  • 1
  • 1
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189
  • This behavior is to follow the HTTP spec. Asking for something which doesn't exist (be it an entity set name wrong, or key value which isn't there) should return 404. If you ask a wrong question about existing resource (for example something is wrong in the $filter), you will get 400 instead. In HTTP 404 is kind of like null (doesn't exist). – Vitek Karas MSFT Jun 05 '13 at 21:51