Can I make a Fluent NHibernate foreign key convention which includes parent key name?

后端 未结 3 653
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 21:07

I have a database schema where the convention for a foreign key\'s name is:

ForeignTable.Name + ForeignTable.PrimaryKeyName

So, for a

3条回答
  •  爱一瞬间的悲伤
    2020-12-17 22:10

    Take a look at conventions and especially at implementing a custom foreign key convention.


    UPDATE:

    Here's an example. Assuming the following domain:

    public class Parent
    {
        public virtual int Id { get; set; }
    }
    
    public class Child
    {
        public virtual string Id { get; set; }
        public virtual Parent Parent { get; set; }
    }
    

    which needs to be mapped to this schema:

    create table Child(
        Id integer primary key, 
        ParentId integer
    )
    
    create table Parent(
        Id integer primary key
    )
    

    you could use this convention:

    public class CustomForeignKeyConvention : IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            instance.Column(instance.Class.Name + "Id");
        }
    }
    

    and to create the session factory:

    var sf = Fluently
        .Configure()
        .Database(
            SQLiteConfiguration.Standard.UsingFile("data.db3").ShowSql()
        )
        .Mappings(
            m => m.AutoMappings.Add(AutoMap
                .AssemblyOf()
                .Where(t => t.Namespace == "Entities")
                .Conventions.Add()
            )
        )
        .BuildSessionFactory();
    

提交回复
热议问题