更新/合并数据库

时间:2018-05-08 20:43:55

标签: c# nhibernate

我有POCO和相应的nHibernate地图文件(Contractor.hbm.xml)
 POCO:

public partial class Contractor : System.IComparable
{
     protected int id;
     protected string name;
     protected string licenseNumber;

     public virtual int ContractorId
     {   get { return this.id; }
         set { this.id = value; }
     }

     public virtual string Name
     {   get { return this.name; }
         set { this.name = value; }
     }

     public virtual string LicenseNumber
     {  get { return this.licenseNumber; }
        set { this.licenseNumber = value; }
     }

     public virtual int CompareTo(object obj)
     {
         if (!(obj is Contractor))
         { throw new System.InvalidCastException("This object is not of type Contractor");  }
         return this.Name.CompareTo(((Contractor)obj).Name);
     }
 }
}

数据库中的表(故意为空的第一行):

ContractorId ContractorName LicenseNumber
0
1 Smith Inc A12345
43 Joe's LLC B4C5t6
4 SureFix Co. 77987
77 ReadyMix 009ABCV

通过GUI,用户更改现有承包商的许可证号 因此,让我们说史密斯公司的许可证号码已更改,POCO现在看起来像::

承包商
    ContractorId:1
    姓名:Smith Inc
    LicenseNumber:New123Num

现在我想将其保存到数据库中。如果我执行SaveOrUpdate(contractor),我会收到NonUniqueObjectException个异常。如果我执行Merge(contractor),则不会发生任何事情,即不会发生异常,但数据库不会使用新的许可证号进行更新。 编辑:我现在看到对象未包含在Session中。我怎么去那里?

public virtual T SaveOrUpdate(T contractor)
{
    NHibernate.ITransaction tx = null;
    try
    {
        using (ITransaction transaction = this.Session.BeginTransaction())
        {
            Session.SaveOrUpdate(contractor);
            transaction.Commit();
        }
    }
    catch (System.Exception ex)
    {
        tx.Rollback();
        Session.Close();
        throw ex;
    }
    return entity;
}

public virtual T Merge (T contractor)
{
    using (ITransaction transaction = this.Session.BeginTransaction())
    {
        try
        {
            Session.Merge(contractor); 
            transaction.Commit();
        }
        catch (System.Exception ex)
        {
            transaction.Rollback();
            Session.Close();
            throw ex;
        }
    }
    return entity;
}

映射文件:

<?xml version="1.0" encoding="utf-8"?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" >
  <class name="Contractor, Infrastructure.Interface"
         table="tblContractor"
         mutable="false">
    <id name="ContractorId" type="Int32" unsaved-value="0">
      <column name="ContractorId" sql-type="int" not-null="true" unique="true" index="PK_tblContractor" />
      <generator class="native" />
    </id>

    <property name="Name" type="String">
      <column name="Name" length="255" sql-type="text" not-null="false" />
    </property>
    <property name="LicenseNumber" type="String">
      <column name="LicenseNumber" length="50" sql-type="text" not-null="false" />
    </property>
  </class>
</hibernate-mapping>

0 个答案:

没有答案