简体   繁体   中英

NHibernate many-to-one with a composite-id entity

How can I map a many-to-one relationship where the "one" entity has a composite-id? For example:

public class SingleEntity  
{  
  public int FirstId{get;set;}  
  public int SecondId{get;set;}  
  public string SomeData{get;set;}  
}  

The entity ManyEntity has (in addition to a primaryKey) columns for both SingleEntity 's FirstId and SecondId, so I want to be able to mape the relationship so that ManyEntity would look like that:

public class ManyEntity  
{  
public int Id{get;set;}  
public SingleEntity Single{get;set;}  
public string Name{get;set;}  
}  

How can I do it using NHibernate?

Fluent allows you to specify composite id mapping using CompositeId() method. However, as we can read in this very method documentation:

Note: Prefer using a surrogate key over a composite key whenever possible.

Composite ids usually require lot of effort for discussable/no gains. If you can , I would strongly advocate to use surrogate key. It's a lot easier.

Yet, if you're stuck with your DB schema, maybe those questions can help you:

If you google those phrases (fluent nhibernate composite id), you'll quickly find out that awful lot of links somehow also contain word "problem" ...

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