gpt4 book ai didi

NHibernate 不允许我在 session 中插入模型,如果它是该 session 失败事务的一部分

转载 作者:行者123 更新时间:2023-12-01 10:56:31 28 4
gpt4 key购买 nike

为什么我在第一次尝试插入模型时从数据库返回错误后不能插入模型:

Report report = null;
using (var session = SessionFactory.OpenSession()) {
try {
using (var transaction = session.BeginTransaction()) {
report = new Report();
session.SaveOrUpdate(report);//Exception: Name field required
transaction.Commit();
}
}
catch { }

try {
using (var transaction = session.BeginTransaction()) {
report.Name = "theName";
session.SaveOrUpdate(report);

//Causes Exception:
//Row was updated or deleted by another transaction (or unsaved-value
//mapping was incorrect): [ReportViewer.DataAccess.Models.Report#22]
transaction.Commit();
}
}
catch { }
}

但是当我更新现有模型时,我得到一个错误,我可以进行修复(在本例中设置一个名称)并再次尝试更新:

Report report = null;
using (var session = SessionFactory.OpenSession()) {
using (var transaction = session.BeginTransaction()) {
report = new Report();
report.Name = "theName";
session.SaveOrUpdate(report);
transaction.Commit();
}
}
using (var session = SessionFactory.OpenSession()) {

//get entity saved from previous session
report = session.Get<Report>(report.Id);

try {
using (var transaction = session.BeginTransaction()) {
report.Name = null;
session.SaveOrUpdate(report);//Exception: Name field required
transaction.Commit();
}
}
catch { }

try {
using (var transaction = session.BeginTransaction()) {

//updates and does not give an error
report.Name = "theName";
session.SaveOrUpdate(report);
transaction.Commit();
}
}
catch { }
}

最佳答案

当发生数据库触发的异常时,NHibernate session 必须 关闭(处置)。不保证在异常后保持一致(内部或与数据库状态)。

请参阅关于 exception handling in the NHibernate reference 的章节.

关于NHibernate 不允许我在 session 中插入模型,如果它是该 session 失败事务的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924813/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com