流利的nhibernate复制一个完整的实体

时间:2013-06-13 12:07:50

标签: c# nhibernate fluent-nhibernate copy

如何在流畅的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();
    }
}

给我一​​些提示。

2 个答案:

答案 0 :(得分:2)

如果您的对象不是可序列化的,并且您只是想要快速一对一的副本,那么您可以使用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>()在内存中创建静态地图,因此只需要定义一次。再次为同一CreateMapTSource调用TDestination将覆盖已定义的地图。同样,调用Mapper.Reset()将清除所有地图。

答案 1 :(得分:1)

你需要

  1. 使用NH
  2. 加载实体
  3. 使用以下方法克隆实体,并创建副本
  4. Evict主要实体
  5. 进行复制更改
  6. 更新副本,不引用主要实体
  7. 克隆方法如下

             /// <summary>
         /// Clone an object without any references of nhibernate
         /// </summary> 
        public static object Copy<T>(this object obj)
        {
            var isNotSerializable = !typeof(T).IsSerializable;
            if (isNotSerializable)
                throw new ArgumentException("The type must be serializable.", "source");
    
            var sourceIsNull = ReferenceEquals(obj, null);
            if (sourceIsNull)
                return default(T);
    
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    

    要使用它,请按以下方式调用

    object main;
    var copy = main.Copy<object>();
    

    要查看有关使用内容的其他一些意见,您可以查看此链接以及Copy object to object (with Automapper ?)

相关问题