Pergunta

I'm currently working on a C# application that imports data from Excel sheets and inserts them in a database. To keep the data layer simple, I'm using NHibernate.

These are two classes I map to the database:

public class Bus
{
    public virtual string Id { get; set; }
    public virtual Bustype Bustype { get; set; }
}

public class Bustype
{
    public virtual string Id { get; set; }
}

I use cascading on the Bustype association in the Bus. My problem with this is, that Bus objects in different Excel sheets reference the same BusType. So I need to do something like this when I want to insert a new Bus:

  • If BusType does not exist in database, insert it first, then insert Bus
  • If BusType exists in database, reference existing BusType in Bus, then insert Bus

Is there any way I can setup NHibernate to automatically do this? Currently I have to check this manually, but I want to avoid this because it's a lot of extra effort:

if (busTypeRepository.GetById(b.BusType.Id) == null) {
                busTypeRepository.Insert(b.Bustype);
}

b.Bustype = busTypeRepo.GetById(b.Bustyp.Id);
busRepository.Insert(b);
Foi útil?

Solução

I would say, that in this scenario your custom approach is simply correct, despite of your note:

Currently I have to check this manually, but I want to avoid this because it's a lot of extra effort

The issue, why it could be hardly managed by NHiberante, is hidden in functionality NHibernate is offering to us, when working with references and their Ids (I.e: Bustype and Bustype.Id)

  • either they do have Id a value == NHibernate expects such an object does exist, no need to INSERT
  • the 'Id' is exactly equal to commonly expected "unsaved-value". We can configure, what is unsaved-value (null, -1, 0...) but we can have only ONE value representing the transient == unsaved instance.

Regardless of the fact that your question is about INSERT, this documeneted section (please, if possible, read it carefully) would give more understanding:

Summary:

If objects coming from client (e.g. Excel sheet) do have the Id pre-set, regardless of the fact they are persisted or not, NHibernate needs our help ...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top