views:

46

answers:

1

We're using FluentNHibernate and we have run into a problem where our object model requires data from two tables like so:

public class MyModel
{
   public virtual int Id { get; set; }
   public virtual string Name { get; set; }
   public virtual int FooId { get; set; }
   public virtual string FooName { get; set; }
}

Where there is a MyModel table that has Id, Name, and FooId as a foreign key into the Foo table. The Foo tables contains Id and FooName.

This problem is very similar to another post here: http://stackoverflow.com/questions/1896645/nhibernate-join-tables-and-get-single-column-from-other-table but I am trying to figure out how to do it with FluentNHibernate.

I can make the Id, Name, and FooId very easily..but mapping FooName I am having trouble with. This is my class map:

public class MyModelClassMap : ClassMap<MyModel>
{
   public MyModelClassMap()
   {
      this.Id(a => a.Id).Column("AccountId").GeneratedBy.Identity();
      this.Map(a => a.Name);
      this.Map(a => a.FooId);

      // my attempt to map FooName but it doesn't work
      this.Join("Foo", join => join.KeyColumn("FooId").Map(a => a.FooName));
   }
}

with that mapping I get this error:

The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'join' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'joined-subclass, loader, sql-insert, sql-update, sql-delete, filter, resultset, query, sql-query' in namespace 'urn:nhibernate-mapping-2.2'.

any ideas?

A: 

I think you misunderstood something here.

Instead of having Id, Name, FooId and FooName in same class you need to create two classes

public class MyModel
{
    public virtual int Id { get; set; }

    public virtual string Name { get; set; }

    public virtual Foo Foo { get; set; }
}

public class Foo
{
    public virtual int Id { get; set; }

    public virtual string FooName { get; set; }
}

And your mapping classes for these:

public class MyModelMapping : ClassMap<MyModel>
{
    public MyModelMapping()
    {
        this.Id(x => x.Id);
        this.Map(x => x.Name);
        this.References(x => x.Foo);
    }
}

public class FooMapping : ClassMap<Foo>
{
    public FooMapping()
    {
        this.Id(x => x.Id);
        this.Map(x => x.FooName);
    }
}

this should help.

But remember Convention other Configuration :)

isuruceanu
Yeah that's how I would traditionally do it, because in essence that is what should be modeled (especially since the DB is setup that way)However my requirement (which comes from up above) does not want to do it that way....Also, it is a simplification of the actual problem for the sake of discussion. The REAL issue is if we did it the way you suggested, class Foo would have a property of type Foo2 in it, and class Bar would have a property of type Foo2...etc etc.That means having a bunch of unnecessary joins/subselects when all I needed was that one property...
puffpio