Fluent NHibernate generates extra columns

后端 未结 1 1516
耶瑟儿~
耶瑟儿~ 2021-02-04 10:49

We are using Fluent NHibernate for data object model in the company i work. A couple of days ago, we encountered an issue that Fluent NHibernate generates an extra column which

1条回答
  •  野性不改
    2021-02-04 11:43

    This often happens when you're using FNH and you have a two-way relationship between entities.

    public class FirstClass
    {
        public virtual SecondClass MyReference { get; set; }
    }
    
    public class SecondClass
    {
        public virtual List ListOfFirstClass { get; set; }
    }
    
    public class FirstClassMap : ClassMap
    {
        public FirstClassMap()
        {
            References(x => x.MyReference);
        }
    }
    
    public class SecondClassMap : ClassMap
    {
        public SecondClassMap()
        {
            HasMany(x => x.ListOfFirstClass);
        }
    }
    

    To fix this you have to override the column name used in either ClassMap, like so:

    public class SecondClassMap : ClassMap
    {
        public SecondClasssMap()
        {
            HasMany(x => x.ListOfFirstClass).KeyColumn("MyReference_id");
        }
    }
    

    or:

    public class FirstClassMap : ClassMap
    {
        public FirstClassMap()
        {
            References(x => x.MyReference).Column("SecondClass_id");
        }
    }
    

    The reason for this is that FNH treats each mapping as a separate relationship, hence different columns, keys, and indexes get created.

    0 讨论(0)
提交回复
热议问题