插入使用LINQ到实体现有行的副本 [英] Insert a copy of existing row using Linq to Entities

查看:100
本文介绍了插入使用LINQ到实体现有行的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架。我有一个自动生成的表的主键和许多其他主数据表foriegn键关系。我们需要一个复制功能,其中我们可以从表中选择任何现有的行和插入在同一个表的副本。

I am using entity framework. I have a table with auto generated primary key and lot of foriegn key relationship with other master data tables. We need a copy functionality, wherein we can select any existing row from the table and insert that as a copy in the same table.

我需要复制所有字段,但它应该是一个不同的记录,以及所需要的程序/ LINQ的一样。

I need to copy all the fields, but it should be a different record, and need the procedure/LINQ for same.

请建议,我应如何进行

推荐答案

您可以这样做:

context.Entry(oCustomer).State = EntityState.Added;

这会导致EF觉得这个实体是一个新的,你叫的SaveChanges 这将是的插入的数据库,而不是的更新

this will cause EF to think this entity is a new one and after you call SaveChanges it will be inserted in the database and not updated.

如果你有一个对象图 - 你需要穿越它,并确保所有儿童实体设置为 EntityState.Unchanged ,否则将被复制后,的SaveChanges

If you have an object graph - you need to traverse it and make sure all child entities are set to EntityState.Unchanged or they will be duplicated after SaveChanges.

这篇关于插入使用LINQ到实体现有行的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆