c# - EF 核心 Web API : foreign key validation

标签 c# database validation asp.net-core entity-framework-core

假设我有这些类(class):

public class User
{
    public int? Id { get; set; }
    ...
}

public class Wallet
{
    public int? Id { get; set; }
    public string Title {get; set;}
    public User Owner { get; set; }
    ...
}

public class WalletCreationDTO 
{
    [Required]
    public string Title {get; set;}
    [Required]
    public int OwnerId { get; set; }
}

[HttpPost]
public async Task<ActionResult> CreateWallet(WalletCreationDto walletDTO) {...}

我必须像这样向前端报告任何错误的参数:

{  
    "errors": {  
        "ownerId": "User by Id does not exist",  
        "title": "Must not exceed 8 characters"  
    }  
}

如何验证 OwnerId?

  • 手动查询数据库似乎无效
  • 默认的 ASP.NET Core 验证似乎没有任何与数据库访问相关的注释

最佳答案

我最终使用了流畅的验证 as suggested .这不是执行此操作的最有效方法,但我正在权衡漂亮的错误和简单的代码。

public class WalletCreateDTO
{
    [Required]
    [MaxLength(20)]
    public string Title { get; set; }

    [Required]
    public int OwnerId { get; set; }

    [Required]
    public string CurrencyCode { get; set; }
}

public class WalletCreateDTOValidator : AbstractValidator<WalletCreateDTO>
{
    public WalletCreateDTOValidator(Data.Database database)
    {
        this.RuleFor(w => w.OwnerId)
            .Must(ownerId => database.Users.Any(user => user.Id == ownerId))
            .WithMessage("User does not exist");
        this.RuleFor(w=> w.CurrencyCode)
            .Must(currencyCode => database.Currencies.Any(currency => currency.Code == currencyCode))
            .WithMessage("Currency does not exist");
    }
}

--- 致 future 阅读本文的任何人 ---

NuGet 包:FluentValidation.AspNetCore

配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddFluentValidation(config =>
        {
            config.RegisterValidatorsFromAssembly(typeof(WalletCreateDTO).Assembly);
        });
}

注意:这似乎在程序集中注册了所有验证器。比如我把我所有的DTO都放在Api.Dtos目录/命名空间里,貌似都注册了,很方便。

此外,还有 swagger 集成:MicroElements.Swashbuckle.FluentValidation

关于c# - EF 核心 Web API : foreign key validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66856919/

相关文章:

database - 在数据库中存储密码的最佳方式

c# - 了解 Boyer Moor

python - 什么是执行 AND/OR 搜索 Django-Postgres 应用程序的有效方法?

c# - 自定义 web.config 部分 (ASP.NET)

jquery - mysql使用like操作报错

ruby-on-rails - 简单的 Rails 格式验证未触发

asp.net - asp.net 中的条件正则表达式验证器

asp.net-mvc - Fluent 验证和 IoC(独特字段)

c# - 如何垂直 "center"对齐多行文字

javascript - 使用 Response.Write JSON 输出从 Jquery 调用 c# asmx Web 服务