【问题标题】:How to clone an entity in Entity Framework Core?如何在 Entity Framework Core 中克隆实体?
【发布时间】:2018-02-05 11:19:21
【问题描述】:

我正在尝试使用 SetValues 方法克隆实体,但出现以下错误:

无法跟踪实体类型“TariffPeriod”的实例,因为已经在跟踪另一个具有与 {'Id'} 键值相同的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

代码如下:

var period2 = _tariffRepository.GetPeriodFull(period.GUID);
var period3 = new TariffPeriod();
_appDbContext.TariffPeriods.Add(period3);
_appDbContext.Entry(period3).CurrentValues.SetValues(period2);

我看到错误是由于主键的值被复制到新实体中。那么,如何在没有键的情况下复制值?

感谢您的帮助 埃里克

【问题讨论】:

  • 你能分离 period2 吗?然后将其Id设置为Add和SetValue之间的period3?

标签: entity-framework


【解决方案1】:

您可以尝试获取 period2 数据的克隆并在分配给 period3 之前修改 Id

var values = db.Entry(period2).CurrentValues.Clone();
values["Id"] = 0;
db.Entry(period3).CurrentValues.SetValues(values);

【讨论】:

    【解决方案2】:

    解决方案 1

    这是我基于@grek40 的解决方案的解决方案,添加了强制转换以避免字符串文字并允许将来重构。

    _appDbContext 辅助方法:

        public TEntity DetachedClone<TEntity>(TEntity entity) where TEntity : class
                => Entry(entity).CurrentValues.Clone().ToObject() as TEntity;
    

    为了你的答案:

        var period2 = _tariffRepository.GetPeriodFull(period.GUID);
        var period3 = _appDbContext.DetachedClone(period2);
        _appDbContext.TariffPeriods.Add(period3);
    

    解决方案 2

    您也可以使用简单的 JSON 深度克隆功能。像魅力一样工作。我更喜欢这种方法,因为第一个解决方案涉及首先使用 .Entry() 附加条目,这可能是不可取的

        public static T Clone<T>(T source)
        {
            var serialized = JsonConvert.SerializeObject(source);
            return JsonConvert.DeserializeObject<T>(serialized);
        }
    

    (ノ◕ヮ◕)ノ✲゚。⋆

    【讨论】:

    • 如果您担心字符串文字,您可以使用 nameof()。
    【解决方案3】:

    将旧时期的值复制到新时期,然后设置具有唯一值的属性(在本例中为主键),最后将实体添加到 DbContext。

    var period2 = _tariffRepository.GetPeriodFull(period.GUID);
    var period3 = new TariffPeriod();
    _appDbContext.Entry(period3).CurrentValues.SetValues(period2);
    period3.Id = 0;
    _appDbContext.TariffPeriods.Add(period3);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-18
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多