简体   繁体   English

在实体框架中复制实体?

[英]copy entity in entity framework?

For example I have a wpf window bound to an customer Entity (let suppose it's cus1). 例如,我有一个绑定到客户实体的wpf窗口(假设它是cus1)。 Then I load another entity from context : 然后我从上下文加载另一个实体:

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

Now I want cus1 = cus2 ? 现在我想要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 ? 这种方式符合我的情况(表格中文本框的内容立即变为cus2的值),但是我想知道是否有任何方法可以使它更短,因为cus1 = cus2不起作用?

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. 如果要使用数据存储中的最新值更新内存中的Customer实体的值,则可以在ObjectContext上使用Refresh方法。

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 AutoMapper will help you by automatically mapping entities to each other with a default setup that you can tweak to your needs. AutoMapper将使用默认设置自动调整彼此之间的映射关系,您可以根据需要进行调整。

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 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. 请记住,如果使用ReferenceType,则使用MemberwiseClone会影响复制引用而不是对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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