是否有最佳实践来复制实体,根据用户输入对其进行一些更改,然后将其重新插入数据库?
其他一些Stackoverflow线程已经提到过,即使数据库中存在相同的主键,EF也会为您处理插入新对象,但我不太确定EF Core是如何处理它的.每当我尝试复制一个对象时,我都会收到错误
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
基本上我只需要一种简洁的方法来复制对象,然后将该副本插回到数据库中,并使Id自动递增.有没有最佳实践或简单的方法,而无需手动将属性设置为null或空?
public Incident GetIncidentByIdForcloning(int id) { try { return _context.Incident.Single(i => i.IncidentId == id); } catch { return null; } }
检索对象后的代码(因为某些字段是自动生成的,如RowVersion,它是一个时间戳):
public IActionResult Clone([FromBody]Incident Incident) { var incidentTocopy = _incidentService.IncidentRepository.GetIncidentByIdForcloning(Incident.IncidentId); incidentTocopy.IncidentTrackingRefId = _incidentService.IncidentRepository.GetNextIdForIncidentCategoryAndType( Incident.IncidentCategoryLookupTableId,Incident.IncidentTypeLookupTableId).GetValueOrDefault(0); incidentTocopy.RowVersion = null; incidentTocopy.IncidentId = 0; //This will fail with or without this line,this was more of a test to see if manually setting would default the insert operation,such as creating a brand new object would normally do. incidentTocopy.IncidentCategoryLookupTableId = Incident.IncidentCategoryLookupTableId; incidentTocopy.IncidentTypeLookupTableId = Incident.IncidentTypeLookupTableId; var newIncident = _incidentService.IncidentRepository.CreateIncident(incidentTocopy); ...
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。