NHibernate不会填充数据库记录

时间:2010-01-17 01:23:55

标签: nhibernate

我是NHibernate的新手,并且一直在使用一些教程。我创建了一个对象(Project)并将其传递给Session.Save(obj)方法。为了测试,我在每个DB字段中都有默认值,并且该方法返回主键但字段为空。我从数据库中删除了默认值,我得到一个SQL错误“无法在第一个字段中插入NULL”。

这是Project类:

public class Project
{
    private int _projectId;
    public virtual int ProjectId 
    {
        get { return _projectId; }
        set { _projectId = value; } 
    }
    private string _projectCode;
    public virtual string ProjectCode 
    {
        get { return _projectCode; }
        set { _projectCode = value; }
    }
    private int _customerKey;
    public virtual int CustomerKey 
    {
        get { return _customerKey; }
        set { _customerKey = value; }
    }
    private DateTime _insertDate;
    public virtual DateTime InsertDate 
    {
        get { return _insertDate; }
        set { _insertDate = value; }
    }
} 

这是映射文件:Project.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping
    xmlns="urn:nhibernate-mapping-2.2"
    assembly="MosaicCrm.Core"
    namespace="MosaicCrm.Core">
    <class name="Project"  >
        <id name="ProjectId">
            <generator class="native"></generator>
        </id>
        <properties name="ProjectCode" ></properties>
        <properties name="CustomerKey"></properties>
        <properties name="InsertDate"></properties>
    </class>
</hibernate-mapping>

这是配置文件。

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="connection.provider">
            NHibernate.Connection.DriverConnectionProvider
        </property>
        <property name="dialect">
            NHibernate.Dialect.MsSql2005Dialect
        </property>
        <property name="connection.driver_class">
            NHibernate.Driver.SqlClientDriver
        </property>
        <property name="connection.connection_string">
            Data Source=localhost;Initial Catalog=MosaicCrm;Integrated Security=SSPI;
        </property>
        <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    </session-factory>
</hibernate-configuration>

以下是控制台应用的片段

var config = new Configuration();
config.Configure();
//config.AddAssembly(typeof(Project).Assembly);
config.AddAssembly("MosaicCrm.Core");

var factory = config.BuildSessionFactory();
//TODO: NHibernate access code here 

ISession session = null;
ITransaction trans = null;
try
{
    session = factory.OpenSession();
    trans = session.BeginTransaction();
    var project = new Project();
    project.CustomerKey = 12;
    project.ProjectCode = "ProjectCode";
    project.InsertDate = DateTime.Now;
    session.Save(project);
    trans.Commit();
    int i = project.ProjectId;
}
catch (Exception ex)
{
    trans.Rollback();
}
finally
{
    session.Close();
}

我缺少什么?

1 个答案:

答案 0 :(得分:0)

您的映射是错误的。用于映射属性的元素是property,而不是properties