In EF CF, how can I change an entity object (detach)?

c# detach ef-code-first entity-framework

Question

I find out the solution:

MyEntity tmp = ctx.Entities.Where<MyEntity>(t => t.Id == objectWithNewValues.Id).SingleOrDefault();
if (tmp != null)
{
    var entityInDb = ctx.Entry(tmp);
    entityInDb.CurrentValues.SetValues(objectWithNewValues);
    ctx.SaveChanges();
}
else
{
    throw new ArgumentException ...
}

Before i used EF4, generate code from schema, the context will have an method "context.ApplyCurrentValue(entity)"

when i try to update a detach object, i can do:

void UpdateObject(Entity e)
{    
     Entity tmp = ctx.Entities.Where(t=>t.id ==e.id);
     ctx.ApplyCurrentValue(e);
     ctx.SaveChannges();
}

Now I have a project using EF4 code first approach and I cannot find "ApplyCurrentValue" method anymore.

so how can I do the update action?

Entity class is a very simple class

public class MyEntity
{
    [Key]
    public Guid Id {get;set;}
    ...
}

my context is a also a very simple class inherte the DBContext

public MyContext : DBContext
{
    public DBSet<MyEntity> Entities {get;set}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Entity<MyEntity>().ToTable("tblMyEntity");
    }
}

And i am trying to do something as below. but value didnt get update into database!

ctx.entities.Attach(entity);
var entityInDb = ctx.Entry(entity);
entityInDb.CurrentValues.SetValues(entity);
context.SaveChanges();

How can i do the update?

1
5
1/6/2014 8:28:27 AM

Popular Answer

late reply, but i think it will help community. change your update method to this

ctx.entities.Attach(entity);
var entry= ctx.Entry(entity);
entry.State = EntityState.Modified;
ctx.SaveChanges();
6
4/28/2012 9:38:39 PM


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