views:

128

answers:

3

I'm importing data that may or may not exist already in my database. I'd like NHibernate to associate any entities with the existing db one if it exists (probably just setting the primary key/id), or create a new one if it doesn't. I'm using S#arp architecture for my framework (MVC 2, NHibernate, Fluent).

I've added the [HasUniqueDomainSignature] attribute to the class, and a [DomainSignature] attribute to the properties I want to use for comparison. The only way I can think to do it (which is not an acceptable solution and may not even work) is the following (psuedo 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.
        }
}

}

As you can see, this is both messy, and non-sensical. Add to that the fact that I've got a half dozen associations on the Book (subject, format, etc), and it doesn't make any sense. There's got to be an easy way to do this that I'm missing. I'm not a novice with NHibernate, but I'm definitely not an expert.

A: 

I might not be understanding the problem, but how can the data "may or may not exist in the database"? For example, if a Book has 2 Authors, how is the relationship stored at the database level if the Author doesn't exist?

It seems as if you're trying to use NHibernate to import your data (or create an entity if it doesn't exist) which doesn't seem correct.

Lester
You are correct, I'm trying to use NHibernate to import my data. Basically, I have a system that has some authors (and books) already in it. I get a feed of data that has more authors (and books) in it. I want to take that feed and import the books/authors into my system that I don't already have. There's a lot more going on in the import as well, which is why I'm translating to the domain model and using NHibernate to import (instead of just keeping it in a dataset and using ADO to import the data.Is this possible?
Jamie
I'm guessing it is possible, but I'm not sure how to do it. My advice is to use a different tool to do the import.
Lester
A: 

Most database implementations support a conditional UPDATE-or-INSERT syntax. Oracle, for example, has a MERGE command. In combination with a Hibernate <sql-insert> block in your mapping you should be able to work something out. I don't know Fluent but I assume it supports this too.

nw
A: 

Just realize I never gave an answer or approved another's answer. I ended up just writing a new SaveOrUpdate which takes a parameter to check for existing before persisting. I also added an attribute to my domain models to overwrite when saving/updating (although in retrospect it's only on updating that it'd be overwriting).

Here's the code if it can help anyone else in this dilemma:

       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);
    }
Jamie