views:

62

answers:

2

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?

Thanks

+1  A: 

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.

Daniel Brückner
+1  A: 

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();
Yakimych