0

我正在使用 Sharp Architecture 创建一个小应用程序,但遇到了一个我无法弄清楚的错误。我认为这与 NHibernte 映射有关。在我的 HttpPost Create() 方法中,我的 SaveOrUpdate 调用试图将 null 插入到表的主键字段中。我的模型中主键的声明是public virtual int Id { get; protected set; }.

我检查了 newSprint.Id,它是零。我认为问题出在我的 NHibernate 映射上,所以我将所有这些都包括在下面。

这是自动映射配置:

public class AutomappingConfiguration : DefaultAutomappingConfiguration
    {
        public override bool ShouldMap(System.Type type)
        {
            return type.GetInterfaces().Any(x =>
                 x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
        }

        public override bool ShouldMap(Member member)
        {
            return base.ShouldMap(member) && member.CanWrite;
        }

        public override bool AbstractClassIsLayerSupertype(System.Type type)
        {
            return type == typeof(EntityWithTypedId<>) || type == typeof(Entity);
        }

        public override bool IsId(Member member)
        {
            return member.Name == "Id";
        }
    }

自动持久性模型生成器:

public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
    {
        public AutoPersistenceModel Generate()
        {
            var mappings = AutoMap.AssemblyOf<Sprint>(new AutomappingConfiguration());
            mappings.IgnoreBase<Entity>();
            mappings.IgnoreBase(typeof(EntityWithTypedId<>));
            mappings.Conventions.Setup(GetConventions());
            mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();

            return mappings;
        }

        private static Action<IConventionFinder> GetConventions()
        {
            return c =>
                   {
                       c.Add<PrimaryKeyConvention>();
                       c.Add<CustomForeignKeyConvention>();
                       c.Add<HasManyConvention>();
                       c.Add<TableNameConvention>();
                   };
        }

提前感谢任何人可以提供的任何帮助。

编辑我发现问题出在表名称约定上。从 AutoMapping 配置中删除它解决了这个问题。我已经删除了无关代码并添加了 TableNameConvention 映射,希望有人可以解释它具体是什么导致了这些问题。

public class TableNameConvention : IClassConvention
{
    public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
    {
        instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));

    }
}
4

1 回答 1

0

您的 IdGenerator 可能不正确。您需要为 PrimaryKey 设置适当的生成器。例如,如果您使用的是 SQL Server,则为 Identity。

我不确定你是如何设置这个的,对 Fluent NH 不是很熟悉。我的猜测是PrimaryKeyConvention

于 2011-08-16T03:25:26.867 回答