NHibernate:存储新对象时无法插入null异常

时间:2018-08-16 10:58:10

标签: nhibernate

我正在使用NHibernate尝试一个非常基本的示例,但是在session.Save()调用上出现异常。 这是我的模型:

public class Student
    {
        public virtual int ID { get; set; }

        public virtual string LastName { get; set; }

        public virtual string FirstMidName { get; set; }
    }

这是Student.hbm.xml文件:

<?xml version="1.0" encoding="utf-8" ?> 

<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" assembly = "NHibernateDemoApp" namespace = "NHibernateDemoApp">

    <class name = "Student"> 
        <id name = "ID">
            <generator class = "native"/> 
        </id> 

        <property name = "LastName"/> 
        <property name = "FirstMidName"/> 
    </class> 

</hibernate-mapping>

这是保存实体的代码:

using (ISession session = this.sessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    savedEntity = (Student) session.Save(new Student { ID = 1, FirstMidName = "Test first name", LastName = "Test Last name"});

                    try
                    {
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        if (!transaction.WasCommitted)
                        {
                            transaction.Rollback();
                        }
                    }
                }
            }

它失败并出现以下错误:

  

无法将值NULL插入表的“ ID”列中   'NHibernateDemoDB.dbo.Student';列不允许为空。插入   失败。

这是怎么了?

1 个答案:

答案 0 :(得分:0)

我使用以下脚本重新创建了表格,现在它可以正常工作了:

CREATE TABLE [dbo].[Student] (
    [ID] INT IDENTITY (1,1) NOT NULL,
    [LastName] NVARCHAR (MAX) NULL,
    [FirstMidName] NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.Student] PRIMARY KEY CLUSTERED ([ID] ASC)
)