0

I have a table in Code First in Entity Framework

public class Foo
{
    public string A;
    public string B;
}

I am trying to update table Foo in the database

Foo foo2 = new Foo
{
    A = "a",
    B = "b"
};

Foo foo1= db.Foo.Find(1);
foo1 = foo2;

and i know foo1 = foo2 wont work because EF will track the reference of foo1 and with
foo1 = foo2 foo1 will get the reference of foo2 and update works if i assign new value to the object one by one

foo1.A = foo2.A;
foo1.B = foo2.B

but is there any way I can achieve this just by copying the data from one object to second? Thanks

so far I have tried this: Shallow Copy

public Foo Clone()
{
    return (Foo)this.MemberwiseClone();
}

but still

foo1 = foo2.Clone();

is not working

Usman
  • 4,615
  • 2
  • 17
  • 33
  • You can find original reference of Foo by key value of your foo2 reference. like db.Foo.First(a=>a.A = foo2.A) and then update this first reference by foo2 and say update actual instance – Ankush Madankar May 10 '16 at 09:39
  • or `db.Foo.Update(foo1)` should work if your `Foo` is part of entity class. – Ankush Madankar May 10 '16 at 09:48

1 Answers1

0

You are looking for deep copy/cloning. To solve your problem you could implement you way of deep copying/cloning your objects. See details here: Deep cloning objects

Or as a simple EF solution you could get out the properties from the object with AsNoTracking() ans set them to a new object. Example:

var originalEntity = Context.MySet.AsNoTracking()
                             .FirstOrDefault(e => e.Id == 1);
Context.MySet.Add(originalEntity);
Context.SaveChanges();

Explanation here: Entity Framework 5 deep copy/clone of an entity

Community
  • 1
  • 1
DDan
  • 8,068
  • 5
  • 33
  • 52