是否有最佳做法来制作实体副本,根据用户输入对其进行一些更改,然后将其重新插入到数据库中?EntityFramework Core - 复制实体并将其放回数据库
一些其他的Stackoverflow线程已经提到EF会为你插入新的对象,即使数据库中存在相同的主键,但我不太确定这是EF Core如何处理它。每当我试图复制一个对象,我得到的
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
基本上,我只需要一个干净的方式来备份复制的对象,使基于用户输入了一些更改,然后插入复制到数据库中的错误,并有正确的Id自动递增。有没有最好的做法或简单的方法来做到这一点,而不必手动设置属性为空或空?
编辑:
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);
...
我意识到我可以制作一个全新的对象并进行左手复制,但这看起来非常低效,我想知道EF Core是否提供了更好的解决方案。
[IDENTITY \ _INSERT设置为OFF时无法在表'表中为标识列插入显式值]的可能重复(http://stackoverflow.com/questions/1334012/cannot-insert-explicit-value-for -identity-column-in-table-table-when-identity) – Curiousdev
你可以分享检索实体的代码,并在修改后尝试插入到dba中吗?基本上在错误的基础上,我会建议将id属性设置为默认为零或null,然后将其重新插入到数据库。 –
我试着将它设置为0,当它试图插入错误仍然抛出,并在本地检查它给-2147483647(我假设来自数据库错误的插入)。我将在一秒钟内在我的OP中编辑一些代码信息。至于好奇的开发者,我宁愿不要永远设置IDENTITY_INSERT,因为这最终会在生产环境中出现,而且如果出现问题,这似乎是一个非常大的潜在蠕虫病毒。 –