0

I have couple of questions with update functionaliy using NHibernate

  1. I have Customer and location entities with 1:n relationship. Customer has location property. While creating/updating customer entity, I just assigned location property and commited changes.

    new Location() { Id = ViewModel.LocationId };
    

    Is it proper way to do it or do I need to retrieve the location entity from db and attach it again like below

    newCust.Location = GetlocationfromDB(ViewModel.LocationId);
    
  2. And how does it work with m:n relationship. I have order and orderitems entities. So, if a newgroup is added/deleted, do I need to check which group is added and get from db and attach it or just groupid will do fine..

1 Answer 1

1
  1. This isn't the right way to do it - it might work if you have your unsaved-value mapping right for the primary key, but the proper way to do it is to use session.Load(ViewModel.LocationId) see http://ayende.com/blog/3988/nhibernate-the-difference-between-get-load-and-querying-by-id

  2. There are a number of ways of dealing with this, but it sounds like you want your relationship to be mapped as a set (to prevent duplicates) rather than a bag. If you map it as a set and use ISet for the property type of the relationship, the duplicates will be handled for you. If however you use a bag, you would need to remove duplicates in your own code. Again, you should be using session.Load to get the group if it's an already existing group.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Martin for your reply, it has been helpful. In your first answer, what does "unsaved-value mapping right" mean.
In your mapping, you can specify an unsaved value for the primary key - NHibernate can then use the value of the primary key to determine if it's a new instance or an existing one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.