在ASP.NET Core

问题描述 投票:0回答:1

为了避免重复的电话号码输入数据库,已经设计了以下自定义验证属性,但是由于某些原因,调用类无法读取

Repository
.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
sealed public class TelephoneAttribute : ValidationAttribute
{
    private readonly IJobRepository _jobRepository; 

    public TelephoneAttribute(IJobRepository jobRepository) 
    {
        _jobRepository = jobRepository;
    }

    public override bool IsValid(object value)
    {
        bool result = false;
        // my logic to avoid duplication of telephone
        var anyDuplicate = _jobRepository.AllJobs.GroupBy(x => x.CustomerContactNumber)
            .Any(g => g.Count() > 1);

        if (anyDuplicate) { result = true; }

        return result;
    }
}

试图在

Model class
中使用此自定义属性,例如:

[Required(ErrorMessage = "**Required**")]
[Display(Name = "Customer Contact Number")]
[DataType(DataType.PhoneNumber)]
[TelephoneAttribute(ErrorMessage = "Duplicate Entry")]

public string CustomerContactNumber { get; set; }

代码行,我会收到以下错误:


CS7036:没有给出的参数对应于“ TelephOneatTribute.telePhoneAttribute(ijobreposority)”所需的参数“ Jobrepository”'

求职指南。谢谢

当前代码无法正常工作。属性是在编译时间生成的,并保存在二进制本身中。当属性实例化时,没有任何应用程序,更不用说任何存储库。
c# asp.net-core
1个回答
0
投票
ISVALID(对象,验证context)

超载。

ValIdationContext

方法允许通过对象检索注射服务? getService(类型ServiceType)。要使用validationContext,ValidationAttribute.RequiresValidationContext属性必须返回truetrue [TelephoneAttribute(ErrorMessage = "Duplicate Entry")] 说,这种验证方式不像数据库中的

sealed public class TelephoneAttribute : ValidationAttribute { public virtual bool RequiresValidationContext => true; public override bool IsValid(object value,ValidationContext context) { bool result = false; if (context.GetService(typeof(IJobRepository) is IJobRepository repository) { // my logic to avoid duplication of telephone var anyDuplicate = repository.AllJobs.GroupBy(x => x.CustomerContactNumber) .Any(g => g.Count() > 1); if (anyDuplicate) { result = true; } } return result; } }
约束那样安全或快速,而在UI中填充表单时也可能是远程查找,即已经可用的功能。 
UNIQUE

仅在有重复的情况下才能起作用。

Count() > 1
首先防止存储重复项,并以一种或另一种方式在所有ASP.NET堆栈中可用的eRemote验证
,随着用户填写表单以确保输入在发布之前有效时,请调用服务器返回服务器。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.