nHibernate更新不适用于现有实体

时间:2012-05-02 12:57:50

标签: nhibernate entity

我正在尝试使用nHibernate更新记录。我尝试了几种解决方案,但它们都没有工作(没有显示错误,也没有更新数据) 第一个代码:

MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Update(post);

第二段代码:

ISession session = GetCurrentSession();
MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Update(post);
session.Update(post);
session.Transaction.Commit();
session = null;

也许有人有建议吗?

4 个答案:

答案 0 :(得分:5)

1)如果您没有使用交易,则需要刷新会话:

var post = _session.Load<Post>(id); //assumes this record exists in the db
post.SomeAttribute=somenewvalue;
_session.SaveOrUpdate(post);
_session.Flush;

2)我没有看到交易正在启动?您需要启动要提交的事务。

using(var transaction = _session.BeginTransaction()){
   _session.SaveOrUpdate(post);
   transaction.commit();
}

答案 1 :(得分:3)

using(var transaction = _session.BeginTransaction()){
   _session.SaveOrUpdate(post);
   transaction.commit();
}

我有这个批量更新返回rowcount = 0但预期是1个异常。但这有效

答案 2 :(得分:1)

UserPost是否正确映射?您使用.hbm.xml文件(请注意hbm)并将xml文件标记为嵌入式资源吗?

enter image description here

根据我的经验,如果实体未映射,NHibernate不会抱怨也不会抛出错误。

实际上更详细地查看您的代码,您并未调用session.Save

答案 3 :(得分:0)

如果你想更新一些持久化实体的字段你不应该调用session.Update()或session.SaveOrUpdate(),你可以使用session.Flush()或者事务:

MyRepository rep = new MyRepository(GetCurrentSession());
UserPost post = rep.GetById(id);
post.ValidTo = date;
rep.Flush(); // session.Flush()

OR

using(var transaction = _session.BeginTransaction()){
   UserPost post = rep.GetById(id);
   post.ValidTo = date;
   transaction.commit();
}
相关问题