Reputation: 5152
I'm using the WCF Data Service client and try to add an object to my datacontext (EntityFramework). The Object is added but I can't use the id afterwards. Is there any possibility that after triggering the SaveChanges method, the object directly gets the auto generated id?
Order order=new Order();
order.name="test";
context.AddObject("Order", order);
if (await context.SaveChanges()) //Extension method on my context to save changes async
{
System.Diagnostics.Debug.WriteLine(order.id); //output: 0
}
My extension method looks like this:
public partial class MyEntities
{
public async Task<bool> SaveChanges()
{
var queryTask = Task.Factory.FromAsync(this.BeginSaveChanges(null,null), asResult =>
{
return(asResult.IsCompleted);
});
return await queryTask;
}
}
I tried also to extend the AddObject
method, but this approch also returns a 0 value:
internal async void AddObject<TResult>(object entity) where TResult : IExtend
{
base.AddObject(entity.ToString().Split('.').Last(), entity);
if (await this.SaveChanges())
{
System.Diagnostics.Debug.WriteLine(((TResult)entity).id); //output: 0
}
}
Upvotes: 2
Views: 1053
Reputation: 5152
I missed the EndSaveChanges
function. When I change my extended function to this, the object id is updated.
public async Task<DataServiceResponse> SaveChanges()
{
var queryTask = Task.Factory.FromAsync(this.BeginSaveChanges(null,null), asResult =>
{
var result = this.EndSaveChanges(asResult);
return result;
});
return await queryTask;
}
Upvotes: 0
Reputation: 13310
If you can use OData V3 then you can set the DataServiceContext.AddAndUpdateResponsePreference
to IncludeContent
. That sends a prefer header to the server and the server will include the entity in the response to the POST request. Client then parses it and applies the values to the client side object. With that the newly generated ID should be visible in the client side OM once the SaveChanges
finishes.
Upvotes: 4