SaveOrUpdate正在尝试将NULL插入主键字段

时间:2011-08-16 00:58:16

标签: nhibernate asp.net-mvc-3 fluent-nhibernate sharp-architecture

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

我检查了newSprint.Id,它是零。我认为这个问题与我的NHibernate Mappings有关,所以我已经包含了以下所有内容。

这是自动配置:

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));

    }
}

1 个答案:

答案 0 :(得分:0)

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

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

相关问题