在自定义验证属性中使用数据库上下文 [英] Using DB Context in a Custom Validation Attribute

查看:90
本文介绍了在自定义验证属性中使用数据库上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Core 2项目中创建一个审价属性.它需要根据数据库中保存的现有值列表来验证该值.

I am trying to create a valdiation attribute in my Core 2 project. It needs to validate the value against a list of existing values held in the database.

下面的代码不起作用,它无法访问数据库上下文.

The code below isn't working, it isn't able to access the DB Context.

任何想法为何/如何纠正?

Any ideas why/how to correct?

public class BibValidatorAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        RaceEntryViewModel raceEntry = (RaceEntryViewModel)validationContext.ObjectInstance;
        ApplicationDbContext _context = new ApplicationDbContext();

        var dbraceEntry = _context.RaceEntries.FirstOrDefault(c => c.Id == raceEntry.Id);

        if(raceEntry.BibNumber != dbraceEntry.BibNumber)
        {
            if (value != null)
            {
                var raceentries = from r in _context.RaceEntries
                                  select r;

                var mycount = raceentries.Count(c => c.BibNumber == raceEntry.BibNumber);

                if (mycount != 0)
                {
                    return new ValidationResult("The bib number entered already exists");
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
            else
            {
                return ValidationResult.Success;
            }
        }
        else
        {
            return ValidationResult.Success;
        }        
    }
}

推荐答案

我发现您可以做的是从ValidationContext中检索数据库上下文,但我没有意识到您可以使用GetService来完成.

What i found you can do is retrieve the DB Context from the ValidationContext which I didn't realize you could do using GetService.

var _context = (ApplicationDbContext)validationContext
                         .GetService(typeof(ApplicationDbContext));

这篇关于在自定义验证属性中使用数据库上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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