views:

823

answers:

3

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

}
+1  A: 

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
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
I'm only against "Address1", "Address2", etc. Though I do understand that this is the only choice in certain circumstances.
Anton Gogolev
+2  A: 

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
In this case how does it know what that foreign key is? Will this support reading aswell and writing?
Dan
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
Very kind of you Erik
Dan
Glad I could help
Erik Öjebo
A: 

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
Oops, I didn't see the "Fluent" part of your title... Sorry about that.
Andy White