Hi Friends,
The ingredients to my question.
1 I use a .NET Framework 4.7.2 ASPX website
2 that connects to a library that holds the EFDatabase context to an OData web api.
3. In my webpage I use a GridView component with ItemType, SelectMethod and UpdateMethod.
When the UpdateMethod is executed I do get the correct entity.
When I call the CreateOrUpdate method in my library I see that trying to do context.UpdateObject() an error is given:
The context is not currently tracking the entity.
I suspect the disconnected state of the asp.net website makes the context disappear. But in the library the context is available in the class.
In the library the context is not null but
context.AttachTo(entitySetName, entity);
tells me The context is already tracking a different entity with the same resource Uri.
How to overcome this issue?
What I have tried:
public virtual bool CreateOrUpdate(DataServiceContext context, T entity)
{
bool result;
try
{
SetupEntityValues(context, entity);
context.SaveChanges();
result = true;
}
catch (ArgumentNullException argEx)
{
Log.Instance.AddException(argEx);
result = false;
LastException = argEx;
if (entity != null)
context.Detach(entity);
}
catch (InvalidOperationException invOpEx)
{
Log.Instance.AddException(invOpEx);
result = false;
LastException = invOpEx;
if (entity != null)
context.Detach(entity);
}
catch (Exception err)
{
Log.Instance.AddException(err);
if (entity != null)
context.Detach(entity);
result = false;
LastException = err;
}
return result;
}
private void SetupEntityValues(DataServiceContext context, T entity)
{
if (entity == null)
throw new ArgumentNullException("No entity given");
if (context == null)
throw new ArgumentNullException("no dbContext given");
var entitySetName = DataServiceContextHelper.GetEntitySetName<T>(context);
var idProperty = entity.GetType().GetProperty("Id") ?? throw new InvalidOperationException("Entity does not have an Id property.");
var id = idProperty.GetValue(entity);
Log.Instance.AddMessage($"Entity name is {entity.GetType().Name}. Id Value = {id}");
if (id.Equals(0))
{
context.AddObject(entitySetName, entity);
}
else
{
try
{
DetachEntitiesWithSameUri(context, entity);
if (!context.IsEntityTracked(entity))
{
context.AttachTo(entitySetName, entity);
context.AddObject(entitySetName, entity);
}
}
catch (Exception err)
{
Log.Instance.AddWarning($"Failed to AttachTo {entitySetName} with Id {id}");
Log.Instance.AddException(err);
}
context.UpdateObject(entity);
}
}