Thomas Winsnes
Thomas Winsnes

Reputation: 1961

How do I map a collection and a property in class A to a single property in class B/C

I have 3 classes that I'm trying to map using fluent nHibernate, but I've hit a wall. I have a collection in class A that refers to class B, B also has a reference to A. So that is a Many-to-one relationship. My problem is that A also has a reference to C (which extends B), and because it already has a reference to A (through B) I don't want to have to create a new property to make the one-to-many relationship between A and C. Is this possible or do I have to make a second property in C?

public class A
{
  public virtual IList<B> AllBInstances { get; set; }

  public virtual C ActiveC { get; set; }
} 

public class B
{
  public virtual A Parent { get; set; }
}

public class C : B
{}

Upvotes: 0

Views: 37

Answers (1)

Firo
Firo

Reputation: 30803

for the given example here are the mappings

class AMap : ClassMap<A>
{
    public AMap()
    {
        Id(x => x.Id);

        HasMany(x => x.AllBInstances)
            .KeyColumn("A_id")
            .Cascade.All();

        References(x => x.ActiveC);
    }
}

class BMap : ClassMap<B>
{
    public BMap()
    {
        Id(x => x.Id);

        References(x => x.Parent, "A_id");
    }
}

class CMap : SubclassMap<C>
{
    public CMap()
    {
    }
}

which would give you

table "A" (
    Id  integer,
   ActiveC_id INTEGER,
   primary key (Id)
)

table "B" (
    Id  integer,
   A_id INTEGER,
   primary key (Id)
)

table "C" (
    B_id INTEGER not null,
   primary key (B_id)
)

Upvotes: 2

Related Questions