如何使用流畅的 nhibernate 自动映射在同一个 table 中引用父实体?

How to reference parent entity in the same table with fluent nhibernate auto mappings?

我正在尝试使用 FluentNHibernate AutoMappings 来创建一个引用其父实体的实体。我能够在 ClassMap<> 的帮助下完成此操作,但现在我想将所有内容移动到 AutoMappings。我有一个具有以下架构的 table:

CREATE TABLE [dbo].[Job]
(
   [Id] INT NOT NULL IDENTITY(1,1), 
   [ParentId] INT NULL, 
   PRIMARY KEY ([Id]), 
   CONSTRAINT [FK_Job_Parent] FOREIGN KEY ([ParentId]) REFERENCES [Job]([Id]) 
)

以及以下 C# 代码:

using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using System;
using System.Configuration;

namespace NHibernateTest
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var sessionFactory = Fluently.Configure()
              .Database(MsSqlConfiguration.MsSql2008.ConnectionString(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
              .Mappings(m =>
              {
                  m.AutoMappings.Add(
                      AutoMap.AssemblyOf<Program>(new MappingConfig()).Conventions.Setup(conv =>
                  {
                      conv.Add<DefaultReferenceConvention>();
                      conv.Add<DefaultHasManyConvention>();
                      conv.Add<SimpleForeignKeyConvention>();
                  }));
              })
              .BuildSessionFactory();

            using (var session = sessionFactory.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                   var jobs = session
                        .QueryOver<Job>()
                        .List<Job>();

                    tran.Commit();
                }
            }
        }
    }

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

        public virtual Job Parent { get; set; }
    }

    public class MappingConfig : DefaultAutomappingConfiguration
    {
        public override bool ShouldMap(Type type)
        {
            return type == typeof(Job);
        }
    }

    public class SimpleForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(Member property, Type type)
        {
            if (property == null)
            {
                return type.Name + "Id";
            }

           return property.Name + "Id";
        }
    }

    public class DefaultHasManyConvention : IHasManyConvention
    {
        public void Apply(IOneToManyCollectionInstance instance)
        {
            instance.Key.Column(string.Format("{0}{1}", instance.EntityType.Name, "Id"));
            instance.LazyLoad();
        }
    }

    public class DefaultReferenceConvention : IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            var col = string.Format("{0}Id", instance.Class.Name);
            instance.Column(col);
            instance.LazyLoad();
        }
    }
}

我得到:

An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.

Foreign key (FK7D5D63A6AE42E0BA:Job [JobId, ParentId])) must have same number of columns as the referenced primary key (Job [Id])

有没有办法只使用自动映射来做到这一点?

您的 DefaultReferenceConvention 似乎与您的 SimpleForeignKeyConvention 冲突。其中一个使用 属性 name 作为列名的基础,另一个使用 属性 type。出于某种原因,Fluent NH 似乎正在使用其中的 both,并且认为您有一个复合键。

删除 DefaultReferenceConvention 并查看是否可以解决问题。反正也没必要,因为 Fluent NH 默认的外键列命名已经是 {Class.Name}Id.

Fluent NH 约定非常适合用宽泛的笔触绘制映射,但它们不是更改单个 属性 的列名称的正确工具。在这种情况下,您应该改为定义 IAutoMappingOverride<T>