【问题标题】:Auto Increment in FLuent Nhibernate and PostgreSQLFluent Nhibernate 和 PostgreSQL 中的自动增量
【发布时间】:2010-10-06 10:06:58
【问题描述】:

我是 Fluent Nhibernate 的新手。

我有一个PostgreSQL 数据库,我想要的是一个自动递增的生成ID。 我没有在 PostgreSQL 中看到自动增量功能,我知道要在 PostgreSQL 中使用自动增量,我必须创建一个序列。

除了序列还有其他方法吗?

如果create sequence 是唯一的方法,你能告诉我应该如何映射它吗? 我尝试使用它并没有成功:

mapping.Id(x => x.Id, "id").GeneratedBy.Sequence("hibernate-sequence");

在使用之前我已经创建了hibernate-sequence

问候

【问题讨论】:

    标签: c# nhibernate postgresql fluent-nhibernate


    【解决方案1】:

    奇怪,但是如果您调用 Save(Object) 而不是 SaveOrUpdate(Object),则使用您的代码插入可以正常工作

    编辑#1

    这对我有用。

    实体:

    public class Human
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
    }
    
    public class HumanMap : ClassMap<Human>
    {
        public HumanMap()
        {
            this.Id(x => x.ID).CustomSqlType("Serial").GeneratedBy.Native();
            this.Map(x => x.Name);
        }
    }
    

    以及带有模式导出的配置:

    static ISessionFactory CreateSF()
    {
        return Fluently
        .Configure()
        .Database(PostgreSQLConfiguration.Standard.ConnectionString("Server=127.0.0.1;Port=5432;Database=fnhtest;User=postgres;Password=password"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
        .ExposeConfiguration(cfg => { new SchemaExport(cfg).Create(false, true); })
        .BuildSessionFactory(); 
    }
    

    【讨论】:

    • 如果Save 有效而SaveOrUpdate 无效...这意味着NH 在C# 集合元素和SQL 表行之间的连接存在问题。可能 NH 找不到元素,因为错误的 PK 分配。
    • 不正确,PostgreSQLConfiguration.Standard 不适用于 GeneratedBy.Native(),请使用最新的 PostgreSQLConfiguration.PostgreSQL82(NHibernate 版本:4.0.0.4000)。
    【解决方案2】:

    我没有在 PostgreSQL 中看到功能自动增量

    这就是 Frank 提到的 SERIAL 数据类型。



    只需将有问题的列创建为 SERIAL,您就有了一个自动增量列:

    创建表 the_table ( id 序列不是 null 主键, other_column varchar(20), ... );

    然后您需要在 Hibernate 中将这些列注释为“自动增量”(因为我不使用 Hibernate,所以我无法告诉您具体是如何完成的)。

    【讨论】:

      【解决方案3】:

      只需使用数据类型SERIAL

      【讨论】:

      • 我在实体中写什么?你能解释一下吗?
      猜你喜欢
      • 2011-04-29
      • 2017-10-31
      • 2013-08-21
      • 2013-03-04
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 2016-08-19
      • 2015-09-03
      相关资源
      最近更新 更多