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

c# detach ef-code-first entity-framework

Question

I come upon the answer:

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 started using EF4, the context would contain a method called "context.ApplyCurrentValue(entity)".

I can perform the following while trying to update a detach object:

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

Now that I have a project utilizing the EF4 code first methodology, I am unable to locate the "ApplyCurrentValue" function.

so how do I go about updating?

A very basic class is the entity class.

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

My context is a fairly simple class that derives from 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'm making the following attempt. but the database was not updated with the value!

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

How do I upgrade my system?

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

Popular Answer

Late response, however I believe it will benefit the community. Change the way you update 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