在自定义验证属性中使用DB上下文

时间:2018-01-18 09:29:40

标签: c# asp.net-core-2.0

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

以下代码无法正常运行,无法访问数据库上下文。

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

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;
        }        
    }
}

1 个答案:

答案 0 :(得分:5)

我发现你可以做的是从ValidationContext中检索数据库上下文,我没有意识到你可以使用GetService。

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