nhibernate:如何设置使用数据库数据的实体验证?

发布于 2024-11-25 04:30:37 字数 2499 浏览 2 评论 0原文

我已经设置了 nhibernate,但在实际保存并提交到数据库之前验证实体时遇到问题。当我加载和更改持久实体时,随后的验证将访问数据库并通过这样做提交事务,从而在知道实际验证结果之前将实体保存在数据库中。

我在 .NET MVC Web 应用程序中使用存储库模式,它是这样的:

public ActionResult Edit(int id, Entity entity)
{
    var repository = new EntityRepository();

    // get persistent entity from nhibernate
    var entityOriginal = repository.GetById(id);

    // copy data from input entity to persistent entity
    entity.CopyDataToEntity(entityOriginal);

    // if validation ok save to database
    // this validations is problematic becouse it needs info from database and uses transaction
    ValidationResult validationResult = entityOriginal.Validate();
    if (validationResult.IsValid())
    {
        repository.Save(entityOriginal);

        // everything ok, redirect to view entity page
        return RedirectToAction("view");
    }
    else
    {
        repository.Evict(prateciList);
        foreach (var message in validationResult.ErrorMessages)
        {
            ModelState.AddModelError(message.Key, message.Value);
        }
        return RedirectToAction("pogledaj");
    }
}

更新:澄清 好的,这是代码:

// get persistent entity from nhibernate
var entityOriginal = repository.GetById(id);
entity.CopyDataToEntity(entityOriginal);
ValidationResult validationResult = entityOriginal.Validate();
  1. 我从数据库中获取持久实体
  2. ,我对其进行更改...现在,如果会话被刷新,它将保留在数据库中,
  3. 我执行entity.Validate(),它从数据库获取另一个实体并在进程中提交(正如您所言)即使从数据库获取也必须提交)!...所以我尝试验证的实体在验证本身期间保留在数据库中。

所以问题是 Entity.Validate() 检查数据库中是否有正确输入的数据,并且由于即使在 session.Get() 上也提交了事务,所以更改的实体会立即保存(有效或无效)。

我的存储库实现是经典的:

public virtual bool Save(T entity)
    {
        var session = SessionProvider.GetRequestSession(this.DatabaseName);
        using (var transaction = session.BeginTransaction())
        {
            try
            {
                session.SaveOrUpdate(entity);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                _log.Error("Could not save object to database.", ex);
                if (transaction.IsActive)
                {
                    transaction.Rollback();

                }
                session.Close();
                return false;
            }
        }

        return true;
    }

如何实现可以检查数据库中内容的验证?

可能的解决方案是在对持久对象进行任何更改之前进行验证,但事实就是如此做起来很痛苦,一定有更好的方法。感谢您的帮助。

I've setup nhibernate but I have problems with validating entity before the actual save and commit to database. As I load and change persistent entity, validation that goes after is accessing the database and by doing so commiting the transaction, thus saving entity in database before the actual validation result is known.

I use Repository pattern in .NET MVC web app and it goes like this:

public ActionResult Edit(int id, Entity entity)
{
    var repository = new EntityRepository();

    // get persistent entity from nhibernate
    var entityOriginal = repository.GetById(id);

    // copy data from input entity to persistent entity
    entity.CopyDataToEntity(entityOriginal);

    // if validation ok save to database
    // this validations is problematic becouse it needs info from database and uses transaction
    ValidationResult validationResult = entityOriginal.Validate();
    if (validationResult.IsValid())
    {
        repository.Save(entityOriginal);

        // everything ok, redirect to view entity page
        return RedirectToAction("view");
    }
    else
    {
        repository.Evict(prateciList);
        foreach (var message in validationResult.ErrorMessages)
        {
            ModelState.AddModelError(message.Key, message.Value);
        }
        return RedirectToAction("pogledaj");
    }
}

UPDATE: clarification
ok here's the code:

// get persistent entity from nhibernate
var entityOriginal = repository.GetById(id);
entity.CopyDataToEntity(entityOriginal);
ValidationResult validationResult = entityOriginal.Validate();
  1. I get the persistent entity from the database
  2. I change it... now if session is flushed it will be persisted in database
  3. I do entity.Validate() which gets another entity from database and commits in process (as you have to commit even for fetching from database)!... so entity I try to validate is persisted in database during the validation itself.

So the problem is that Entity.Validate() check the database for correctly inputed data, and since transaction is commited even on session.Get(), changed entity is saved (valid or invalid) right there.

My repository implementation is classic:

public virtual bool Save(T entity)
    {
        var session = SessionProvider.GetRequestSession(this.DatabaseName);
        using (var transaction = session.BeginTransaction())
        {
            try
            {
                session.SaveOrUpdate(entity);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                _log.Error("Could not save object to database.", ex);
                if (transaction.IsActive)
                {
                    transaction.Rollback();

                }
                session.Close();
                return false;
            }
        }

        return true;
    }

How can I achieve validation that can check stuff in database?

Possible solution be to validate before I make any changes to persistent object, but this is such a pain to do there must be a better way. Thank you for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北音执念 2024-12-02 04:30:37

我发现的解决方案非常丑陋,但它有效:

  1. 从数据库获取原始实体
  2. 将其克隆(复制所有数据)到新实例
  3. 修改并验证新实例
  4. 如果验证正常,则将所有内容从新实例复制到原始实例并保存

仍在寻找不过更好的解决方案。

The solution I've found is very ugly but it works:

  1. get original entity from database
  2. clone it (copy every data) to new instance
  3. modify and validate new instance
  4. if validation ok, copy everything from new instance to original and save

Still looking for a better solution though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文