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?
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.
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 .
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With