无法使用NHibernate将数据插入数据库

时间:2018-08-14 14:43:45

标签: c# postgresql nhibernate fluent-nhibernate

我是NHibernate的新手,我写的代码很简单,应该将有关用户的信息插入数据库中 代码在

下面

UserClassModel

 class Users
    {
        public virtual int id { get; set; }
        public virtual string username { get; set; }
        public virtual string password { get; set; }
        public virtual string role { get; set; }
        public virtual bool deleted { get; set; }
        public virtual DateTime create_date { get; set; }

    }

UserMapClass

 class UserMap : ClassMap<Users>
{
    public UserMap() 
    {
        Id(x => x.id);
        Map(x => x.username);
        Map(x => x.password);
        Map(x => x.deleted);
        Map(x => x.role);
        Map(x => x.create_date);


    }

}

我尝试使用NHibernate将数据插入数据库的连接

class Connection
    {
        public Connection() 
        {
            var sefact = createFactory();
            using (var session = sefact.OpenSession())
            {
                using (var txt = session.BeginTransaction()) 
                {
                    var users = new Users
                    {

                        username = "jakhongir",
                        password = "2356+"


                    };
                    session.Save(users);
                }
            }




        }
        private static ISessionFactory createFactory()
        {

            string connectionString = "Server=127.0.0.1; Port=5433; User Id=smartwarehouse; Password=$smart#2018;Database=warehouse;";
            IPersistenceConfigurer config = PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString);
            FluentConfiguration configuration = Fluently.Configure().Database(config).Mappings(m => m.FluentMappings.Add(typeof(UserMap)));



            return configuration.BuildSessionFactory();



        }

这是代码,我无法将其插入数据库,它给出以下错误 enter image description here

这是数据库的一部分 enter image description here

1 个答案:

答案 0 :(得分:0)

将模型类从“用户”重命名为“用户”(通常,对模型使用单数名称是一种好习惯,因为它代表单个实体)

class User
{
    public virtual int id { get; set; }
    public virtual string username { get; set; }
    public virtual string password { get; set; }
    public virtual string role { get; set; }
    public virtual bool deleted { get; set; }
    public virtual DateTime create_date { get; set; }

}

映射类必须派生自ClassMap:

// Creating the map class
public UserMap:ClassMap<User>
{
    // The constructor of Mapping class
    public UserMap()
    {
        Id(x => x.id);
        Map(x => x.username);
        Map(x => x.password);
        Map(x => x.deleted);
        Map(x => x.role);
        Map(x => x.create_date); 
    }  
}