1
我想在NHibernate中開發我的Hello World程序。NHibernate入門
我的代碼如下:
MyClass.cs
----------
using System.Collections.Generic;
using System.Text;
using System;
using NHibernate.Collection;
using NHibernate.Mapping;
using Iesi.Collections;
namespace NHibernate__MyClass
{
public class MyClass
{
int id;
string name;
int _value;
public MyClass()
{
id = 0;
name = "";
_value = 0;
}
public virtual int Id
{
get { return id; }
set { id= value; }
}
public virtual string Name
{
get { return name; }
set { name= value; }
}
public virtual int Value
{
get { return _value; }
set { _value= value; }
}
}
}
MyClass.hbm.xml
---------------
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernate__MyClass" assembly="NHibernate__MyClass">
<class name="MyClass" table="MyClass">
<id name="Id">
<column name="ID" sql-type="int" not-null="true"/>
<generator class="native" />
</id>
<property name="Name">
<column name="Name" not-null="true" />
</property>
<property name="Value">
<column name="Value" not-null="true" />
</property>
</class>
</hibernate-mapping>
Program.cs
----------
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernate__MyClass
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.Id = 1;
myClass.Name = "Hello World!";
myClass.Value = 100;
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
session.BeginTransaction();
session.Save(myClass);
session.Transaction.Commit();
Console.ReadLine();
}
}
}
App.config
----------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section
name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
/>
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=NHibernate;Integrated Security=True</property>
<mapping assembly="NHibernate__MyClass" />
</session-factory>
</hibernate-configuration>
</configuration>
SQL Table
---------
CREATE TABLE [dbo].[MyClass](
[ID] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
[value] [int] NOT NULL
) ON [PRIMARY]
但是該程序產生一異常:
異常消息:{「無法插入:[NHibernate__MyClass.MyClass] [SQL:INSERT INTO MyClass的(名稱,值)VALUES(?,?);選擇SCOPE_IDENTITY()]「}
內部異常消息:{」不能將值NULL插入'ID'列'NHibernate.dbo.MyClass';列不允許爲空,INSERT失敗。\ r \ n聲明已終止。「}
可能是什麼問題?
NHibernate的DLL版本= 2.0.0.2002
精彩的建議!!!!!! – 2009-06-19 21:40:39