gpt4 book ai didi

c# - 流畅的 nhibernate 复制一个完整的实体

转载 作者:行者123 更新时间:2023-11-30 16:17:30 29 4
gpt4 key购买 nike

如何在 fluent nhibernate 3.3.1 中最好地复制实体实例;我从数据库中读取了一个对象,得到了一个对象,现在我更改了这个对象的一些值。这个几乎没有变化的对象要我保存。

我曾尝试将 Id 设置为 0,但这是行不通的,我还在我的 Entityclass 中编写了一个 Clone 方法。这是我的方法。

public class Entity: ICloneable
{
public virtual int Id { get; protected set; }

object ICloneable.Clone()
{
return this.Clone();
}

public virtual Entity Clone()
{
return (Entity)this.MemberwiseClone();
}
}

你能给我一些提示吗?

最佳答案

如果您的对象不可序列化并且您只是在寻找它们的快速一对一副本,您可以使用 AutoMapper 轻松完成此操作:

// define a one-to-one map
// .ForMember(x => x.ID, x => x.Ignore()) will copy the object, but reset the ID
AutoMapper.Mapper.CreateMap<MyObject, MyObject>().ForMember(x => x.ID, x => x.Ignore());

然后当你复制方法时:

// perform the copy
var copy = AutoMapper.Mapper.Map<MyObject, MyObject>(original);

/* make copy updates here */

// evicts everything from the current NHibernate session
mySession.Clear();

// saves the entity
mySession.Save(copy); // mySession.Merge(copy); can also work, depending on the situation

我为自己的项目选择了这种方法,因为我与围绕记录复制的一些奇怪要求有很多关系,我觉得这让我对它有了更多的控制。当然,我项目中的实际实现会有所不同,但基本结构大致遵循上述模式。

请记住,Mapper.CreateMap<TSource, TDestination>()在内存中创建一个静态映射,因此只需要定义一次。打电话CreateMap同样的TSourceTDestination如果 map 已经定义,将覆盖它。同样,调用 Mapper.Reset()将清除所有 map 。

关于c# - 流畅的 nhibernate 复制一个完整的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17086700/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com