JatSing
JatSing

Reputation: 4977

copy entity in entity framework?

For example I have a wpf window bound to an customer Entity (let suppose it's cus1). Then I load another entity from context :

customer cus2 = context.customers.where(x=>x.id=10).FirstOrDefault();

Now I want cus1 = cus2 ? I can do this way :

cus1.name = cus2.name;
cus1.address = cus2.address;
...
...

This way meets my case (the content of textboxs in the form change immediately into values of cus2) but I wonder if there is anyway to make it shorter since cus1=cus2 doesn't work ?

Thanks

Upvotes: 0

Views: 958

Answers (3)

mikus
mikus

Reputation: 3215

You could also use Serialization or Reflection, to do it on your own. However both oof the methods are slower then writing it directly.

Take a look at this article. Maybe you will find it helpful:

http://www.codeproject.com/KB/dotnet/CloningLINQ2Entities.aspx

Edit: Btw. Remember, using using MemberwiseClone, in case of ReferenceTypes will effect in copying the references, not objects.

Upvotes: 1

SvenG
SvenG

Reputation: 5195

You can use the memberwise Clone method to make a shallowcopy of a business object: See http://msdn.microsoft.com/de-de/library/system.object.memberwiseclone.aspx

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39888

If you want to update the values of a Customer entity in memory with the newest values in the datastore you can use the Refresh method on your ObjectContext.

Here is the documentation.

In your case it would look like:

context.Refresh(RefreshMode.StoreWins, cus1);

If you really want to map two entities you could have a look at AutoMapper. AutoMapper will help you by automatically mapping entities to each other with a default setup that you can tweak to your needs.

Upvotes: 1

Related Questions