Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate one-to-one vs 2 many-to-one

Tags:

c#

nhibernate

In his blog, Ayende suggests that using a one-to-one is probably not the best way to implement a traditional 1:1 object relationship (e.g. customer.Name == name.Customer).

  1. How do I choose when to use the one-to-one relationship?
  2. Why should I choose 2 one-to-many relationships
  3. How does the one-to-one work (There are no FK columns generated)

One to one:

One-to-one

2 many-to-one:

enter image description here

like image 253
Darbio Avatar asked Nov 05 '22 21:11

Darbio


1 Answers

Only reason I've come across for using one-to-many mapping is because of performance.

I've initially went with one-to-one until project hit the wall with performance issue. Problem happens because you usually can't have lazy loading for one-to-one mapping on reverse side. E.g. when you have entity A which can (but doesn't have to) have related entity B on that mapping. In that case, for each entity A you load, entity B is also loaded. This is done to prevent error with checking if related object exists. Proxy for lazy loading would mislead you to think that related entity exists, even when it does not. If you check for related entity existence like this you will be in a problem

if (entityA.EntityB == null) HandleNoEntityB();

If you use one-to-many mapping however, lazy loading is no problem, because developer is working with a collection for which we can create proxy.

if (entityA.EntitiesB.Count == 0) HandleNoEntityB();

This doesn't have to be a problem if you can make an assumption in your system that entity A always has exactly one related entity B. In that case, you should set contrained="true" on that mapping.

like image 132
Nikola Radosavljević Avatar answered Nov 14 '22 23:11

Nikola Radosavljević