Choose between one-to-one and component in NHibernate
I am trying to map classes User and Profile, just as the following:
public class User
{
public long ID { get; set; }
public string LoginName { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
//the ID is the same with User's ID
public long ID { get; protected set; }
public string NickName { get; set; }
public Gender Gender { get; set; }
}
So, they can be mapped as both one-to-one and componenet relationship. And I find some people appraise the component and think one-to-one is a bad practise, why? For performance reason? But they are designed as two separate tables in many scenarios(asp.net2.0 Membership, for example).
How should I choose? Which aspects should I co开发者_开发问答nsider? I know component means "value object" but not an enitity, but does this mean some further things?
ps: And what confused me more is the opinion that the many-to-one should be used even it's one-to-one relationship in real world!
The key should be in your use cases for this class. Don't take ASP.NET Membership as an example, because its design is terrible.
You need to answer these questions:
- Does a Profile make sense as an entity of its own?
- Do you have references to the Profile anywhere else in your domain?
- Can you have a User without a Profile?
- Does it have a behavior of its own?
- Would you extend (inherit) Profile for some reason?
- Do most use cases just deal with the user (and its LoginName, not just the ID) but not the profile?
If most questions are true, you have a good case for using one-to-one (I disagree with @Falcon; this is actually one of the legitimate uses for one-to-one)
Otherwise, a Component will work fine. It doesn't have an ID, so you can remove that property.
You should use neither.
One-To-One
You have the user and the profile in different database tables but both share a mutually exclusive PK: See http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/
Pretty bad design practice for relational databases, it's messy and does not necessarily enforce constraints for the relationship.
Component
You can use component to get a clean Object-Model from a messy relational database, profile and user data are both stored in the same database table but they should be separated in your object model (like you want it, judging from your code). Lazy loading probably isn't supported, which will cause high database traffic.
Reference
Imho, you should use a Reference. It's conceptual kinda like one-to-one but a user references a profile. The profiles can be stored in their own table, can be loaded lazily (performance) and are not dependent on a user.
Regarding your confusion: Just read the link I supplied. Technically, you need a many to one for a properly designed database-scheme, as that is what is technically possible and will be mapped. I know it's confusing. If you just need to map one-side, think of a reference instead of a one-to-one.
精彩评论