【问题标题】:NHibernate repository for SQLite sometimes saves entity to wrong tableSQLite 的 NHibernate 存储库有时会将实体保存到错误的表中
【发布时间】:2011-11-25 17:40:54
【问题描述】:

我有这个仓库:

 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 语句。 Nhibernate 是由 XML 配置的。我正在对所有存储库方法使用 NUnit 测试。 这是我正常工作一年后第一次出现在我的应用中。

可能的解决方案: - 我应该使用 session.Save(string entityName, object entity) 吗?但是怎么做?如何获取 entityName?

【问题讨论】:

  • 您的映射是如何定义的? IEntity 是如何定义的?
  • @DanielA.White 请查看我的更新。

标签: c# nhibernate sqlite


【解决方案1】:

我认为你的问题在于这句话My code is running on more then one thread。我会重新审视这一点,因为会话是not 线程安全的。另请参阅此S.O. post 了解更多信息。

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

【讨论】:

    【解决方案2】:

    这听起来绝对像是您的代码中的错误。可能有一些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();
            }
        }
    

    【讨论】:

    • 另外,请确保您遵循 Rippo 的建议:确保您没有在不同线程之间使用相同的会话。
    猜你喜欢
    • 2015-05-03
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多