我正在嘗試使用靜態擴展方法創建一些驗證規則,IRuleBuilderOptions因此在為創建和更新我的物件創建驗證器時,我不必不斷重復自己。
出于某種原因,我country.Id在MustAsync唯一檢查中不斷收到 CS1061 錯誤。我試過用括號和 替換箭頭函式return,試過async/ await。它們都會導致相同的錯誤。Intellisense 顯示它country是 type Country,并且Id是具有公共 getter 和 setter 的公共財產,所以我不確定我錯過了什么?我嘗試編譯,以防它只是 Intellisense 問題,但編譯失敗并出現相同的錯誤。
注意:使用 VS2022 / .Net6
public class Country
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Code2 { get; set; } = string.Empty;
public string Code3 { get; set; } = string.Empty;
public int DisplayOrder { get; set; } = 1000;
public bool Enabled { get; set; } = true;
}
public class CountryCreateValidator : AbstractValidator<Country>
{
public CountryCreateValidator(IApplicationDbContext dbContext)
{
RuleFor(x => x.Name).Name(dbContext);
RuleFor(x => x.Code2).Code2(dbContext);
RuleFor(x => x.Code3).Code3(dbContext);
}
}
public class CountryUpdateValidator : AbstractValidator<Country>
{
public CountryUpdateValidator(IApplicationDbContext dbContext)
{
RuleFor(x => x.Id).NotEmpty();
RuleFor(x => x.Name).Name(dbContext);
RuleFor(x => x.Code2).Code2(dbContext);
RuleFor(x => x.Code3).Code3(dbContext);
}
}
public static class CountryRules
{
public static IRuleBuilderOptions<Country, string> Name<Country>(this IRuleBuilder<Country, string> ruleBuilder, IApplicationDbContext dbContext) =>
ruleBuilder.NotNull().NotEmpty().MaximumLength(64)
.MustAsync((country, name, cancellationToken) =>
{
return dbContext.Countries.AllAsync(x => x.Id == country.Id /* error here */ || x.Name != name, cancellationToken);
}).WithMessage(FvConstants.UNIQUE);
public static IRuleBuilderOptions<Country, string> Code2<Country>(this IRuleBuilder<Country, string> ruleBuilder, IApplicationDbContext dbContext) =>
ruleBuilder.NotEmpty().Length(2).Matches("^[A-Z]{2}$").WithMessage("{PropertyName} must be two uppercase letters")
.MustAsync((country, code2, cancellationToken) =>
{
return dbContext.Countries.AllAsync(x => x.Id == country.Id || x.Code2 != code2, cancellationToken);
}).WithMessage(FvConstants.UNIQUE);
public static IRuleBuilderOptions<Country, string> Code3<Country>(this IRuleBuilder<Country, string> ruleBuilder, IApplicationDbContext dbContext) =>
ruleBuilder.NotEmpty().Length(3).Matches("^[A-Z]{3}$").WithMessage("{PropertyName} must be three uppercase letters")
.MustAsync((country, code3, cancellationToken) =>
{
return dbContext.Countries.AllAsync(x => x.Id == country.Id || x.Code3 != code3, cancellationToken);
}).WithMessage(FvConstants.UNIQUE);
}
public class FvConstants
{
public const string UNIQUE = "{PropertyName} must be unique";
}
這是一個螢屏截圖,顯示了正確鍵入country引數和我收到的錯誤...

uj5u.com熱心網友回復:
因為Country是您的方法的泛型引數的名稱,而不是型別名稱。只需<Country>從簽名中洗掉:
public static IRuleBuilderOptions<Country, string> Name(...
public static IRuleBuilderOptions<Country, string> Code2(...
public static IRuleBuilderOptions<Country, string> Code3(...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354375.html
下一篇:如何填充網頁上的文本框
