开发者

How do I use Fluent nHibernate to map a multi-table entity using a foreign key from the primary entity using an FK->PK relationship?

This is the basic example from hbm-style nhibernate.

http://ayende.com/blog/2327/multi-table-entities-in-nhibernate

public class Person
{
  public int PersonId {get;set;}
  public string Name {get;set;}
  public string AddressStreetAddress {get;set;}
  public string AddressZipCode {get;set;}
}

In the database, Person has an Id primary key, a name field, and an address foreign key. Address has its own primary key, a street address field and a zip code f开发者_StackOverflow中文版ield.

The correct answer is "Don't do it.". Unfortunately I'm stuck with an entity object that exposes the Id and Name of another entity and those are used elsewhere still. At the moment, this object won't be persisted back to the database through nHibernate.

I think the way to do this is to use the address as the table of the entity and add the Person fields from the Join(). What are the consequences of doing this as an intermediate step in a change-over?


I think the way to do this is to use the address as the table of the entity and add the Person fields from the Join(). What are the consequences of doing this as an intermediate step in a change-over?

This was a bad idea because the only Id you could map to is the Id of the address which can be shared between multiple persons.

Instead, add a private/protected property for Address to Person, map Address and reference the address using the following Fluent call.

References(Reveal.Member<Person, Address>("Address")).Column("address_id")

Then, you can use AddressStreetName and AddressZipCode to pass through to Address.StreetName and Address.Zipcode. After that, it's a simple matter of refactoring the rest of the system to be sane again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜