Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top