是否有最佳实践来复制实体,根据用户输入对其进行一些更改,然后将其重新插入数据库?
其他一些 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);
...
我意识到我可以创建一个全新的对象并进行左手复制,但这似乎效率非常低,我想知道 EF Core 是否提供更好的解决方案。