EF模型验证针对数据库 [英] EF Model Validation against database

查看:231
本文介绍了EF模型验证针对数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用EF 5模型验证,以避免在数据库中重复的值,所以我用这样的模型类:

I want to use EF 5 model validation to avoid duplicate values in the database, so I'm using a model class like this:

[Table("MeasureUnits")]
public class MeasureUnit : IValidatableObject
{
    public int MeasureUnitId { get; set; }

    public string Symbol { get; set; }

    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        using (MeasureUnitRepository rep = new MeasureUnitRepository())
        {
            MeasureUnit measureUnit = rep.FindDuplicateBySymbol(this);

            if (measureUnit != null)
                yield return new ValidationResult(
                    "There is another unit with this symbol, you can't duplicate it", 
                    new[] { "Symbol" });
        }
    }

信息库类创建的DbContext,实现IDisposable,必须找到重复的逻辑,这一切只是工作按预期。

The repository class creates the DbContext, implements IDisposable, has the logic to find the duplicate and it all works just as intended.

然而,使用我意识到为每个插入或更新进行两次验证调试器,所以存储库(和的DbContext)被实例化和处置也两次。

However, using the debugger I realized the validation is performed twice for every insert or update, so the repository (and DbContext) gets instantiated and disposed twice also.

除此之外,还有另外的DbContext生活在控制器,但只是没有找到使用它的模型类里面,除了包含的DbContext模型的构造函数的方式,但我觉得这是不正确的解决方案。

Besides that, there is another DbContext living in the controller but just don't find the way to use it inside the model class, other than including the DbContext in the model's constructor, but I feel it's not the right solution.

有没有更好O正确的方式来实现这一验证?

Is there a better o "right" way to achieve this validation?

先谢谢了。

推荐答案

当你必须去到数据库中,那么你需要使用的DbContext 的DbContext 有一个名为执行validateEntity 可重写方法。看到这篇文章:实体框架验证

When you have to go to the database then you need to use DbContext and DbContext has an Overridable method called ValidateEntity. See this article: Entity Framework Validation.

我把code我在另一个答案使用这里

I put the code I use in another answer here

和更多关于如何我结构验证的MVC 的位置。

And more about how I've structured the validation in MVC here.

此外,实例化你的资料库里面上下文很可能导致你的悲伤。该库将需要共享的上下文。你可以把背景下为你的工作单位并把它传递到存储库中的构造函数,或者你可以换背景下在自己的工作单位,并通过在

Also, instantiating a context inside your repository is likely to cause you grief. The repositories will need to share a context. You could treat the context as your unit of work and pass it into the repository in the constructor, or you could wrap the context in your own unit of work and pass that in.

这篇关于EF模型验证针对数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆