Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i update an entity object (detach) in EF CF?

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?

like image 616
jojo Avatar asked Apr 04 '11 07:04

jojo


People also ask

How do you update an entity?

How to Update a new record in to a existing entity using update entity action? First you need to check the id if id exist then you can use the update entity action and if id is new then you can used the create entity action.

How do I detach an EF core entity?

If you want to detach an object that is already attached to the context, set the state to Detached . If you want to load entities from the DB without attaching them at all to the context (no change tracking), use AsNoTracking .

What difference does AsNoTracking () make?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.


1 Answers

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();
like image 160
Abdul Qadir Memon Avatar answered Sep 19 '22 02:09

Abdul Qadir Memon