views:

148

answers:

1

Hello there,

I am trying to implement Bidirectional Mapping with Fluent NHibernate Mapping.

Code snippet from Domain classes:

public class Template
{
    public virtual int? Id { get; set; }

    public virtual string Title { get; set; }

    public virtual TemplateGroup TemplateParentGroup { get; set; }
}

public class TemplateGroup
{
    public virtual int? Id {get; set;}

    public virtual string Title { get; set; }

    public IList<Template> Templates { get; set; }
}

Code snippet from Mapping classes:

public class TemplateMap : ClassMap<Template>
{
    public TemplateMap()
    {
        Id(x => x.Id).UnsavedValue(null).GeneratedBy.Native();
        Map(x => x.Title).Not.Nullable().Length(150);
        References(x => x.TemplateParentGroup).Column("TemplateGroupId").Not.Nullable(); 
    }
}

public class TemplateGroupMap : ClassMap<TemplateGroup>
{
    public TemplateGroupMap()
    {
        Id(x => x.Id).UnsavedValue(null).GeneratedBy.Native();
        Map(x => x.Title).Not.Nullable().Length(150);
        HasMany(x => x.Templates).Table("Template").AsBag().Cascade.AllDeleteOrphan();
    }
}

However, when I am exporting schema, it results in two FK columns in Template table, Here is the output SQL for Template table:

   create table [Template] (
    Id INT IDENTITY NOT NULL,
   Title NVARCHAR(150) not null,
   TemplateDoc VarBinary(MAX) not null,
   *TemplateGroupId INT not null,
   TemplateGroup_id INT null,*
   primary key (Id)
)

As I am already specifying the FK ref. column name as "TemplateGroupId",

How can I avoid TemplateGroup_id to be generated?

+1  A: 

Try using the KeyColumn on the HasMany mapping

HasMany(x => x.Templates).KeyColumn("TemplateGroupId").Table("Template").AsBag().Cascade.AllDeleteOrphan();
Rafael Mueller
Thank you!, It solved the issue. Is value of 'KeyColumn' specifies the common referencing column in two tables, Template and TemplateGroup?
inutan