2013-01-16 75 views
3

我只是想開始學習NHibernate,並與一個非常簡單的POCO測試時,我已經有問題。我發現了沒有留存例外,這裏是我的代碼如下所示:NHibernate映射異常。沒有persister:NHibernateTesting.Account

Account表:

create table Account 
(
    AccountID int primary key identity(1,1), 
    AccountName varchar(10), 
    CreateDate datetime 
) 
go 

Account類:

public class Account 
{ 
    public virtual int AccountID { get; set; } 
    public virtual string AccountName { get; set; } 
    public virtual DateTime CreateDate { get; set; } 

    public Account() 
    { 
     AccountID = 0; 
     AccountName = ""; 
     CreateDate = new DateTime(); 
    } 
} 

映射文件,Account.hbm.xml(是的,它嵌入進入組裝):

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        namespace="NHibernateTesting" assembly="NHibernateTesting"> 
    <class name="Account" table="Account"> 
    <id name="AccountID"> 
     <generator class="native"/> 
    </id> 
    <property name="AccountName" /> 
    <property name="CreateDate" /> 
    </class> 
</hibernate-mapping> 

Co在配置文件nfig部分:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> 
    <session-factory> 
     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> 
     <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> 
     <property name="connection.connection_string">My connection string</property> 

     <mapping assembly="NHibernateTesting" /> 

    </session-factory> 
</hibernate-configuration> 

最後,進行調用的代碼:

using (var session = NHibernateHelper.GetASession()) 
{ 
    using (var tran = session.BeginTransaction()) 
    { 
     var newAccount = new Account(); 
     newAccount.AccountName = "some name"; 

     session.Update(newAccount); // Exception thrown here. 

     tran.Commit(); 
    } 
} 

有人能看到我在做什麼錯誤或我爲什麼會得到這個例外,我讀過在網絡上,這個問題與映射有關,但我在這個例子中看不到什麼錯誤。

+0

也許Hibernate的Session是沒有正確配置?你能否給出來源NHibernateHelper? – proskor

+0

順便說一句,每當你創建一個新的實例,你應該調用session.Save或session.SaveOrUpdate而不是session.Update。 – proskor

回答

2

我已經複製了所有的映射和​​代碼,正如你所顯示的,它正在工作。除了:

var newAccount = new Account(); // NEW 
... 
session.Update(newAccount); // Update throws exception: 

NHibernate.StaleStateException:批量更新返回了意外的行從更新 計數;實際行數:0;預計:1個

新對象必須通過保存:session.Save(newAccount);

當你說,該映射文件被標記爲嵌入的資源......這是很難說究竟是什麼錯。請儘量仔細地遵循此鏈接(並重新檢查你的項目),具有相當不錯的體驗鏈有關沒有留存 excepiton:

+0

由於我創建了另一個控制檯項目,與項目的名稱末尾添加了一個2(NHibernateTesting2)並且它工作正常,項目本身一定是錯誤的,因爲編譯器沒有選擇映射文檔正好。 WTH VS2012 ?! – IWriteApps

+0

是的,這是可能的,這些「不正確」很難找到。很高興看到你已經設法解決它。 –

2

的發生是由於無效此錯誤映射配置。你應該檢查你爲會話工廠設置的.Mappings。基本上搜索「.Mappings(」在您的項目,並確保你在下面行中指定正確的實體類。

.Mappings(m => m.FluentMappings.AddFromAssemblyOf<YourEntityClassName>()) 
0

我改變我的列名標識解決了這個錯誤。因爲我已經做了第一TemplateId所以它顯示這個錯誤,但是當我改變了外地標識它得到了解決。因此,它是NHibernate的或果園有標識字段或者主鍵標識的要求。