简体   繁体   中英

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

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 (eg 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:

一对一

2 many-to-one:

在此处输入图像描述

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. Eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM