NHibernate:对附加实体的显式更新调用
虽然我已经使用NHibernate一段时间了,但我仍然误解了这个ORM的一些基本概念。假设我有一个名为“Blog”的类,我加载了一个持久化实例,如下所示:NHibernate:对附加实体的显式更新调用,nhibernate,Nhibernate,虽然我已经使用NHibernate一段时间了,但我仍然误解了这个ORM的一些基本概念。假设我有一个名为“Blog”的类,我加载了一个持久化实例,如下所示: using (var tx = Session.BeginTransaction()) { var myBlog = Session.Get(10); tx.Commit(); } 如果我现在更改此实例的属性,NHibernate似乎会自动检测未保存的更改,并在事务提交时生成更新 这导致以下语句的作用完全相同: using
using (var tx = Session.BeginTransaction())
{
var myBlog = Session.Get(10);
tx.Commit();
}
如果我现在更改此实例的属性,NHibernate似乎会自动检测未保存的更改,并在事务提交时生成更新
这导致以下语句的作用完全相同:
using (var tx = Session.BeginTransaction())
{
var myBlog = Session.Get(10);
myBlog.Title = "Changed title";
tx.Commit();
}
using (var tx = Session.BeginTransaction())
{
var myBlog = Session.Get(10);
myBlog.Title = "Changed title";
Session.Update(myBlog); // why is this necessary?
tx.Commit();
}
我看不出和NHProf有什么不同。那么,为什么存在显式更新方法?我应该在什么时候使用它?实体并不总是与会话连接。例如,您可以使用接受某些实体的webservice with方法,并在db中进行更新:
[WebMethod]
void UpdatePerson(int id, string name){
using (var tx = Session.BeginTransaction(){
var person = new Person(id, name);
Session.Update(person);
tx.Commit();
}
}
此代码在数据库中执行更新而不发出select。实体并不总是与会话连接。例如,您可以使用接受某些实体的webservice with方法,并在db中进行更新:
[WebMethod]
void UpdatePerson(int id, string name){
using (var tx = Session.BeginTransaction(){
var person = new Person(id, name);
Session.Update(person);
tx.Commit();
}
}
此代码在数据库中执行更新而不发出select。Wow!这似乎对我当前的应用程序有很大的性能优势。对于我当前的更新方法,我总是先使用id获取附加的实体,然后从DTO中逐个复制所有属性。这当然会导致2 db的往返,因为我必须在更新之前先获取实体!谢谢你的提示!哇!这似乎对我当前的应用程序有很大的性能优势。对于我当前的更新方法,我总是先使用id获取附加的实体,然后从DTO中逐个复制所有属性。这当然会导致2 db的往返,因为我必须在更新之前先获取实体!谢谢你的提示!