SaveChanges() in Entity Framework not working?

c#-3.0 entity-framework

Question

I use entity framework with Visual Studio 2008, sure it was SP1 both .NET Framework and VS itself. My application is develop in n-tier environment. First step I convert data from context to collection and serialize to user.

HRMSDBContext context = new HRMSDBContext();

List<InHouseTrainingHead> heads = context.InHouseTrainingHead.ToList<InHouseTrainingHead>();

foreach (InHouseTrainingHead head in heads)
{
    context.Detach(head);
}

return heads;

After user changes some data and click save then this list return to save method.

HRMSDBContext context = new HRMSDBContext();

foreach (InHouseTrainingHead head in lists)
{
    context.Attach(head);
    context.ApplyPropertyChanges(head.EntityKey.EntitySetName, head);
}

context.SaveChanges();

Unfortunately after SaveChanges() nothing happen. How can I solve this problem?

1
2
6/8/2018 10:09:40 AM

Accepted Answer

You are not using ObjectContext.ApplyPropertyChanges the way it is intended to be used. You need two instances of the entity - a unmodified one attached to the context and the detached modified one. The changes are then applied to the unmodifed attached entity, it becomes modified, and you can save the changes. So you must not attach the modified entity but load the entity from the database prior to calling ObjectContext.ApplyPropertyChanges.

2
7/13/2010 10:49:40 AM

Popular Answer

To extend Daniel Brückner's answer - what happens in your sample is that you are trying to ApplyPropertyChanges between the head object and itself. Obviously, there are no changes, thus nothing is saved. If you don't want to fetch the record from the DB, however, you can set the EntityState of the newly attached entity to Modified manually. In this case it will be saved in the DB:

HRMSDBContext context = new HRMSDBContext();

foreach (InHouseTrainingHead head in lists)
{
    context.Attach(head);
    ObjectStateEntry addedEntity = context.ObjectStateManager.GetEntry(head);
    addedEntity.ChangeState(EntityState.Modified);
}

context.SaveChanges();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow