【问题标题】:Using Merge instead of SaveOrUpdate使用合并而不是 SaveOrUpdate
【发布时间】:2026-01-25 22:25:01
【问题描述】:

我有下面的代码。它有时会给出运行时错误:

具有相同标识符值的不同对象已经存在 与会话关联

我看到了一个建议使用Merge 而不是SaveOrUpdate 的解决方案。尝试时(请参阅注释掉的行)。我得到一个编译错误:

类型 T 必须是引用类型才能将其用作参数 泛型类型或方法中的T

此错误的解决方案是在类声明中添加T : class。它已经有T : new()。当我将其更改为“类”时,会出现其他编译错误。

'T' 必须是具有公共无参数构造函数的抽象类型 为了将其用作泛型类型或方法中的参数“T”

另见GetDefaultInstance()

我该怎么做?

public class GenericNHibernateDataService<T, ID> : Interface.Data.IGenericDataService<T, ID> where T : new() 
    public virtual T GetDefaultInstance()
    {
        return new T(); // compile error when changing to T : class
        // Cannot create an instance of the variable type 'T' because it does not have the new constraint
    }

    public virtual T SaveOrUpdate (T entity)
    {
        NHibernate.ITransaction tx = null;

        try
        {
            tx = this.Session.BeginTransaction();
            this.Session.SaveOrUpdate (entity);
            //Session.Merge(entity); //The type T must be a reference type in order to use it as a parameter `T` in the generic type or method

            tx.Commit();
        }
        catch (System.Exception ex)
        {
            tx.Rollback();
            throw ex;
        }
        return entity;
    }
    ...

}

【问题讨论】:

  • 您是否尝试添加两个约束:where T : class, new()
  • 行得通!如果您愿意,可以将其发布为答案。
  • 完成。很高兴这有效。

标签: c# nhibernate


【解决方案1】:

添加两个约束:

where T : class, new()

【讨论】: