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>块在你的映射中,你应该能够解决一些问题。我不知道流利,但我认为它也支持。

相关问题