c# - EntityFramework Core - 复制实体并将其放回数据库

标签 c# asp.net-mvc entity-framework asp.net-core entity-framework-core

复制实体、根据用户输入对其进行一些更改,然后将其重新插入数据库是否有最佳实践?

一些其他 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 是否提供了更好的解决方案。

最佳答案

因此,在创建这个线程之前,我比最初偶然发现它的时候更仔细地浏览了“可能重复”线程,并且有一个不太受欢迎的解决方案,我忽略了它基本上只是捕获了所有从数据库中检索对象时立即获取值 - 并且它不会在此过程中检索对该对象的引用。我的代码现在看起来像这样:

try
{
    var incidentToCopy = _context.Incident.Single(i => i.IncidentId == id);
    return (Incident) _context.Entry(incidentToCopy).CurrentValues.ToObject();
}

关于c# - EntityFramework Core - 复制实体并将其放回数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43586915/

相关文章:

c# - 索引超出数组范围

c# - 在 OnRegistered 方法中将标签添加到 NotificationHub

C# Web 服务 - 然后返回 最后 - 先发生什么

asp.net - ASP.NET 最大请求大小的临时覆盖

c# - 将对象序列化为 JSON 时循环引用检测到异常

c# - 如何设置 C# 元素以将 css 从本地 .css 文件内联到 HTML 中? PreMailer.Net 可以做到这一点吗?

c# - 与区域同名的 Controller - Asp.Net MVC4

.net - 无法加载文件或程序集 'Antlr3.Runtime (1)' 或其依赖项之一

entity-framework - Entity Framework 代码优先和生产者/消费者模式

c# - Context.SaveChanges() 挂起,似乎是由于 Entity Framework 中的嵌套事务和 FK 约束