1

我正在導入可能存在或可能不存在於我的數據庫中的數據。我希望NHibernate將任何實體與現有的數據庫關聯(如果存在的話可能只是設置主鍵/ ID),或者如果不存在,則創建一個新的實體。我爲我的框架(MVC 2,NHibernate,Fluent)使用S#arp架構。獲取現有實體(如果它存在或創建一個新實體)

我已將[HasUniqueDomainSignature]屬性添加到類中,並且將[DomainSignature]屬性添加到要用於比較的屬性中。我能想到這樣做(這不是一個可接受的解決方案,甚至有可能不會正常工作)的唯一方法是以下(僞C#):

foreach (Book importedBook in importedBooks){ 
    foreach (Author author in importedBook.Authors){ 
     if (!author.IsValid()){ // NHibernate Validator will check DomainSignatures 
      author = _authorRepository.GetByExample(author); // This would be to get the db object with the same signature, 
           //but I don't think I could even update this as I iterate through it. 
     } 
} 

}

正如你所看到的,這既是凌亂和非感性。除此之外,我在這本書(主題,格式等)上有六個關聯,並且沒有任何意義。有一個簡單的方法可以做到這一點,我錯過了。我不是NHibernate的新手,但我絕對不是專家。

回答

0

只是意識到我從來沒有給出答案或批准他人的答案。我最終只寫了一個新的SaveOrUpdate,它在持久之前使用一個參數來檢查現有的。我還爲我的域模型添加了一個屬性,用於在保存/更新時覆蓋(儘管回想起它只是在更新時纔會覆蓋)。

下面的代碼,如果它可以幫助其他人在這個兩難問題:

 public TEntity SaveOrUpdate<TEntity>(TEntity entity, bool checkForExistingEntity) 
    { 
     IRepository<TEntity> repository = new Repository<TEntity>(); 
     if (checkForExistingEntity) { 

      if (entity is Entity) { 
       IEnumerable<PropertyInfo> props = (entity as Entity).GetSignatureProperties(); 
       Dictionary<string, object> parameters = 
        props.ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(entity, null)); 
       TEntity duplicateEntity = repository.FindOne(parameters); 
       if (duplicateEntity != null) { 
        // Update any properties with the OverwriteOnSaveUpdate attribute 
        foreach (var property in RepositoryHelper.GetUpdatableProperties(typeof(TEntity))) 
        { 
         object initialValue = property.GetValue(entity, null); 
         property.SetValue(duplicateEntity, initialValue, null); 
        } 
        // Fill in any blank properties on db version 
        foreach (var property in typeof(TEntity).GetProperties()) 
        { 
         if (property.GetValue(duplicateEntity, null) == null) { 
          object initialValue = property.GetValue(entity, null); 
          property.SetValue(duplicateEntity, initialValue, null); 
         } 
        } 
        return duplicateEntity; 
       } 
      } 
     } 
     return SaveOrUpdate(entity); 
    } 
0

我可能不會理解問題,但數據如何「可能存在或可能不存在於數據庫中」?例如,如果一本書有兩位作者,那麼如果作者不存在,關係如何存儲在數據庫級?

看起來好像你試圖使用NHibernate導入你的數據(或創建一個實體,如果它不存在的話),這似乎不正確。

+0

你是正確的,我試圖使用NHibernate的導入我的數據。基本上,我有一個系統已經有一些作者(和書籍)。我收到了一個有更多作者(和書籍)的數據源。我想採取這種飼料,並將書籍/作者導入我尚未擁有的系統中。在導入中還有很多事情發生,這就是爲什麼我要轉換爲域模型並使用NHibernate導入(而不是將其保存在數據集中並使用ADO導入數據。) 這是可能的? – Jamie 2010-04-29 21:06:46

+0

我猜這是可能的,但我不知道該怎麼做。我的建議是使用不同的工具來進行導入。 – Lester 2010-04-30 11:49:40

0

大多數數據庫實現支持條件UPDATE或INSERT語法。例如,Oracle有MERGE command。結合Hibernate <sql-insert>塊在你的映射中,你應該能夠解決一些問題。我不知道流利,但我認爲它也支持。

相關問題