You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FluentValidation自定义扩展调用MustAsync访问属性报CS1061错误如何解决

问题原因

你遇到的CS1061报错由泛型参数命名冲突导致:
你在CountryRules类的三个扩展方法声明时,额外加了和实体类同名的泛型参数<Country>,这个泛型占位符的优先级高于你定义的Country实体类,编译器会将方法内所有的Country类型识别为无约束的泛型参数,自然无法识别Id属性。Intellisense的类型提示属于误判,编译时会按实际的泛型参数逻辑处理,所以会触发报错。

解决方案

直接移除三个扩展方法名后的<Country>泛型声明即可,修改后的代码如下:

public static class CountryRules
{
    public static IRuleBuilderOptions<Country, string> Name(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 || x.Name != name, cancellationToken);
            }).WithMessage(FvConstants.UNIQUE);

    public static IRuleBuilderOptions<Country, string> Code2(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(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);
}

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:27:07