SQLite的NHibernate存储库有时会将实体保存到错误的表中

本文关键字:保存 实体 错误 存储 NHibernate SQLite | 更新日期: 2023-09-27 18:15:39

我有这个存储库:

 public class RepositorySQLite : IRepository
    {
        public void Add<T>(T entity)
        {
            using (ISession session = SessionProviderSqLite.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(entity);
                transaction.Commit();
            }
        }
      ...
     }

我是这样使用它的:

public class Entity1: IEntity
{
        public virtual long SomeProperty { get; set; }
}
public class Entity2: IEntity
{
        public virtual long AnotherProperty { get; set; }
}
 IEntity entity = new Entity1();
 entity.SomeProperty = 123;

 IRepository repository = new RepositorySQLite();
             repository.Add(entity);
实体映射:

每个实体都有自己的表Entity1, Entity2,…一切正常,但有时Entity1存储在Entity2表中。我的代码在多个线程上运行。我用的是Lock语句。hibernate是通过XML配置的。我对所有存储库方法使用NUnit测试。在我的应用程序正常工作一年后,这是第一次发生这种情况。

可能的解决方案:-我应该使用session吗?保存(字符串实体名称,对象实体)?但如何?我如何获得entityName?

SQLite的NHibernate存储库有时会将实体保存到错误的表中

我认为你的问题出在这句My code is running on more then one thread。由于会话是not线程安全的,我将重新讨论这个问题。更多信息请参见s.o.s post。

黄金法则是:- Make sure that you are not using the same session between different threads .

这听起来肯定像是代码中的一个bug。可能,有一些repository.Add(entity),其中entity是对意外的"EntityX"的引用。

要使用session.Save(string entityName, object entity)过载,请尝试下面的代码:

    public void Add<T>(T entity)
    {
        using (ISession session = SessionProviderSqLite.OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(typeof(T).FullName, entity)
            transaction.Commit();
        }
    }