NHibernate-更新代码示例 [英] NHibernate - code example for update
本文介绍了NHibernate-更新代码示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在整天试图将我的对象之一保存为版本,但无济于事.请指出我在做错什么,因为在Clear()
调用之后尝试了SaveOrUpdate
,Merge()
和Update()
.
I've been trying all day to get one of my object to be saved with versions but to no avail. Please point out what I'm doing wrong, as I've tried SaveOrUpdate
, Merge()
and Update()
after a Clear()
call.
业务对象:
public class MappedTest
{
public virtual Guid TestID { get; set; }
public virtual int VersionID { get; set; }
public virtual byte[] Content { get; set;}
public virtual DateTime DateSaved { get; set; }
}
映射:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping ...>
<class name="TestImp.Definition.MappedTest, PythonTest" table="Tests">
<id name="TestID" unsaved-value="00000000-0000-0000-0000-000000000000">
<generator class="guid"/>
</id>
<version name="VersionID" column="VersionID" />
<property name="Content" column="TestObject" type="BinaryBlob"/>
<property name="DateSaved" column="Date"/>
实际代码:
using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
if(session.Get<MappedTest>(mappedTest.TestID) == null)
{
session.Save(mappedTest);
}
else
{
session.Clear();
session.Update(mappedTest);
}
transaction.Commit();
}
}`
谢谢.
推荐答案
对于插入,请尝试使用:
For insert try just with:
using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())
{
MappedTest mappedTest =new MappedTest();
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(mappedTest);
transaction.Commit();
}
}
用于更新:
using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())
{
MappedTest mappedTest =session.Get<MappedTest>(..an Id..);
mappedTest.YourProperty="newValue";
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(mappedTest);
transaction.Commit();
}
}
如果需要,请尝试使用session.Flush()
强制执行数据库操作.
If you need it try use a session.Flush()
to force database operations.
这篇关于NHibernate-更新代码示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文