简体   繁体   中英

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

您可以使用memberwise Clone方法来制作业务对象的浅表副本:请参阅http://msdn.microsoft.com/de-de/library/system.object.memberwiseclone.aspx

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM