Can't submit new object to WCF DataService because of Primary Key constraint
I've got a SQL database that uses Guid's for PK's and upon insert, it generates a NewId(). I have an EF data context setup pointing to that database with the primary keys setup with the Entity key:true, Setter:private and StoreGeneratedPattern:Identity because I want the DB to manage the keys and not have code set the PK property.
I have an OData (System.Web.Data.Services.DataService) endpoint to access this data (just like: Hanselman did.
I have another app that has a service reference to this service. Upon trying to create a new object from this reference (i.e. Product), the ProductId Primary Key is being defaulted to Guid.Empty when doing
var serviceEntities = new ServiceEntities(serviceUri); //OData endpoint
var product = new Product();
product.Name = "New Product";
serviceEntities.AddToProducts(product);
serviceEntities.SaveChanges(); // error happens here
When debugging, I look at the Product.ProductId property and it's set to Guid.Empty. When called SaveChanges, I do not want the ProductId field to be sent to the service. The response I get is:
Error processing request stream. Property 'ProductId' is a read-only property and cannot be updated. Pleas开发者_Go百科e make sure that this property is not present in the request payload.
Is there a way to do this or what can I do to get this setup correctly and still have the DB generated the keys.
Here is the same setup as the Product example above.
What I ended up doing was adding a ChangeInterceptor
. This works but its not the preferred way of doing it.
[ChangeInterceptor("Products")]
public void OnChangeApplications(Product product, UpdateOperations operations)
{
if (operations != UpdateOperations.Add) return;
if (product.ProductId == Guid.Empty)
{
product.ProductId = Guid.NewGuid();
}
}
精彩评论