c# - NHibernate - 条目永远不会被保存到 Nhibernate 中的数据库中
问题描述
我正在尝试创建一个具有 4 个属性的对象;1x ID 和 3x 对其他表的引用。
我知道我不应该将 NHibernate“session.Save()”与 sql Insert 语句进行比较,但我仍然希望它在请求/线程完成后将其保存在数据库中。这就是我的代码的样子:
var session = Home.Instance.GetSession();
session.Begin();
var profile = session.Get<ProfilePO>(profileId);
var queue = session.Get<QueuePO>(queueId);
var telephone = session.Get<TelephonePO>(telephoneId);
var newObject = new UserProfileControlledQueueMembersPO
{
Profile = profile,
Queue = queue,
Telephone = telephone
};
session.Save(newObject);
var idOfNewObj = newObject.Id; //This gets the correct value from the autoincrementing ID in the mysql database.
var newObjFromCacheOrDb = session.QueryOver<UserProfileControlledQueueMembersPO>().Where(x => x.Id == idOfNewObj).List().FirstOrDefault();
//newObjFromCacheOrDb actually return the correct values of the created object
“会话”来自包装类:
private int _transactionCount;
private ITransaction _transaction;
private ISession Session { get; set; }
public void Begin()
{
if (_transactionCount <= 0)
{
_transaction = Session.BeginTransaction();
_transactionCount = 0;
}
_transactionCount++;
}
public object Save<T>(T ob) where T : TEntityType
{
if (_transactionCount <= 0)
throw new Exception("Save is not allowed without an active transaction!");
return Session.Save(ob);
}
在 NHibernate 的日志中,我发现了这个:
DEBUG NHibernate.SQL (null) - INSERT INTO Profile_Queue_Telephone (ProfileId, QueueId, TelephoneId) VALUES (?p0, ?p1, ?p2);?p0 = 7283 [Type: Int32 (0:0:0)], ?p1 = 27434 [类型:Int32 (0:0:0)],?p2 = 26749 [类型:Int32 (0:0:0)]
调试 NHibernate.SQL (null) - SELECT LAST_INSERT_ID()
DEBUG NHibernate.SQL (null) - 选择 this_.Id 作为 id1_45_0_, this_.ProfileId 作为 profileid2_45_0_, this_.QueueId 作为 queueid3_45_0_, this_.TelephoneId 作为 phone4_45_0_ FROM Profile_Queue_Telephone this_ WHERE this_.Id = ?p0;?p0 = 74 [类型: Int32 (0:0:0)]
我很困惑为什么这不在数据库上执行,因为 NHibernate 清楚地将它存储在某种缓存中,因为我能够检索数据。如果是因为回滚,我假设会在日志中说明,MySql 服务器上发生了回滚。
所以我的问题是我在这里缺少什么,我该怎么做才能将对象插入数据库?
编辑:
值得注意的是,我对 NHibernate 很陌生。我正在做一个 4 年以上的项目,用 NHibernate 编写。
解决方案
您的包装器方法session.Begin()
启动了一个事务,但您从未调用相应的Commit
方法来永久保存对数据库的更改。否则,更改将被回滚,并且您的数据库实际上不会受到影响。您的包装方法之一应该是调用_transaction.Commit
,找到该方法并调用它。
推荐阅读
- apache-spark - Spark Streaming Direct Approach 中的 Exactly once 语义
- c# - c#如果匹配则返回值,否则继续
- json - vuetify 2 v-data-table 嵌套 for 循环
- c++ - 汇编指令是如何指示的?
- html - 具有动态高度/宽度的容器内的方形弹性项目
- c - 在链表中插入节点的函数
- javascript - 无法解析模块“module://AssetRegistry.js”
- matrix - 在 CUDA 的平铺矩阵乘法中访问矩阵作为其转置
- sql - CSV 文件元数据验证(与现有 SQl 表比较)
- javascript - Next.js 中的 getInitialProps 是什么