2

Is there a way of writing an NHibernate mapping so that you can have an entity that is composed of fields from different DB tables?

For Example is I have a Person and Address table, I want address fields to appear in my person object.

I want an entity like this:

public class person
{
    public virtual Guid Key{get; set;}
    public virtual string Name {get; set;}
    public virtual string Age {get; set;}
    public virtual string Address1 {get; set;} //from address table
    public virtual string Address2 {get; set;} //from address table

}
Dan
  • 29,100
  • 43
  • 148
  • 207

3 Answers3

3

If you are using Fluent NHibernate you can use WithTable, as in this example:

public class PersonMap : ClassMap<Person>
{
  public PersonMap()
  {
    Id(x => x.Key, "[Key]"); // Explicitly specify escaped column name to 
                             // avoid problems with reserved words
    Map(x => x.Name);
    Map(x => x.Age);

    WithTable("Address", m =>
    {
      m.Map(x => x.Address1);
      m.Map(x => x.Address2);
    });
  }
}
Erik Öjebo
  • 10,821
  • 4
  • 54
  • 75
  • In this case how does it know what that foreign key is? Will this support reading aswell and writing? – Dan Feb 25 '09 at 11:19
  • I guess it just tries to find a foreign key relationship between the tables and uses that one. I wrote a little sample app using the mapping above and a person class corresponding to the one in your question. Both reading and writing worked fine. – Erik Öjebo Feb 25 '09 at 11:25
  • Seems WithTable no longer exists in Fluent 1.2? – Peter McEvoy Jan 25 '12 at 09:13
1

I think here's what you need. Not sure about support on Fluent NHibernate part, as well as I'm not sure about the validity of this idea.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • Thanks. The idea of un-normalising my objects? Is this not one of the aims of Nhibernate? to separate my domain model from my database model? – Dan Feb 25 '09 at 11:22
  • I'm only against "Address1", "Address2", etc. Though I do understand that this is the only choice in certain circumstances. – Anton Gogolev Feb 25 '09 at 11:25
0

You could also consider using a many-to-many table between Person and Address. In that case, it might make sense to have a property "Addresses" that can just hold a list of however many addresses you want.

You can do a mapping (or whatever collection mapping works best) with a mapping to accomplish this.

Andy White
  • 86,444
  • 48
  • 176
  • 211