I am new to NHibernate and have been working with some tutorials. I created an object (Project) and passed it to the Session.Save(obj) method. To test, I had default values in each DB field and the method returned the primary key but the fields were blank. I removed the default values from the DB and I get a SQL error "cannot insert NULL into the first field".
Here is the Project class:
public class Project
{
private int _projectId;
public virtual int ProjectId
{
get { return _projectId; }
开发者_如何学C 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; }
}
}
Here is the mapping file: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>
Here is the config file.
<?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>
Here is a snippet of the console app
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();
}
What am I doing missing?
Your mapping is wrong. The element used to map a property is property
, not properties
.
精彩评论