Reputation: 23
I'm having a problem that I thought was easy to resolve. This is my scenario (Entity framework 4 disconnected entities using self tracking). Let's say I have 2 entities: Users, Orders. From an asp.net page a get from the database 1 user and 1 order.
const int userId = 1;
const int orderId = 1;
var userManager = new UserManager();
var orderManager = new OrderManager();
var user = userManager.GetUser(userId);
var order = channelManager.GetChannel(channelId);
user.Orders.Add(order);
Now I need to create a function that updates the user adding the order to it.
I wrote something like:
public bool UpdateUser(User user)
{
context.AttachTo("Users", user);
var stateMgr = context.ObjectStateManager;
var stateEntry = stateMgr.GetObjectStateEntry(user);
for (int i = 0; i < stateEntry.CurrentValues.FieldCount; i++)
{
bool isKey = false;
string name = stateEntry.CurrentValues.GetName(i);
foreach (var keyPair in stateEntry.EntityKey.EntityKeyValues)
{
if (string.Compare(name, keyPair.Key, true) == 0)
{
isKey = true;
break;
}
}
if (!isKey)
{
stateEntry.SetModifiedProperty(name);
}
}
context.ApplyCurrentValues("Users", user);
return context.SaveChanges() > 0;
}
I don't have any error on this function and debugging everything seems to be ok, but when I check on the database the entity is not updated as expected. I thought update a disconnected entity was something simple but apparently is not. Can someone explaing me the logic between the update the entire graph of disconnected object with EF4? Please if you can I need to undestand the logic and not have a collection of links to look at. I already spent some time looking on internet but I'm finding so many approches that I'm not sure which one is correct.
Thanks
Upvotes: 1
Views: 854
Reputation: 653
With Self Tracking Entities you have to use the ApplyChanges() method to sync the change on a context instead (and not attach).
The applychanges will go to the graph to update the linked object/collection.
Public Function UpdateEntity(entity As Entity) As Entity
Using dbContext As New EntityContext()
dbContext.EntitySet.ApplyChanges(entity)
dbContext.SaveChanges()
dbContext.Refresh(Objects.RefreshMode.StoreWins, entity)
End Using
Return entity
End Function
The refresh is optionnal, it is here only to push back the last value of the database. By the way the refresh doesn't update the linked object.
Upvotes: 0
Reputation: 364269
I don't see anything related to Self tracking entities in your code. Anyway STEs with ASP.NET don't work very well.
What is your code supposed to do? It looks like you want to do this:
public bool UpdateUser(User user)
{
context.AttachTo("Users", user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
return context.SaveChanges() > 0;
}
But it will not save relations. I just answered some related question about working with detached graphs.
Upvotes: 1