【问题标题】:MinLength/Range Data Annotation does not work in NUnit testMinLength/Range 数据注释在 NUnit 测试中不起作用
【发布时间】:2020-09-03 10:17:27
【问题描述】:

如果我在模型类中使用 MinLen 和 Range,则测试不会引发我期望的异常。

MaxLength 反而按预期工作。

我也有同样的行为,使用其他数据库作为 sqlite、sqlserver。

[TestFixture]
public class PostgreSqlRangeFixture
{
    [Test]
    public void TestRange_MustThrow()
    {
        using (var ctx = new LocalDbContext()) {
            ctx.Database.EnsureCreated();

            User user = new User() { FirstName = "12", LastName = "too short", Age = -100 };
            ctx.Users.Add(user);
            ctx.SaveChanges();
        }
    }
}

public class LocalDbContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        const string psw = "marcos";
        string dbName = "test_" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss.fff");
        var cs = $"Host=192.168.99.100;Username=postgres;Password={psw};Database={dbName}";
        optionsBuilder.UseNpgsql(cs);
    }
}

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

    [Required]
    [MaxLength(2)]
    public string FirstName { get; set; }

    [Required]
    [MinLength(20)]
    public string LastName { get; set; }

    [Required]
    [Range(0,150)]
    public int Age { get; set; }
}

【问题讨论】:

  • EF Core(当前)不使用/考虑这些数据注释。

标签: c# entity-framework-core data-annotations


【解决方案1】:

EF Core 仅使用这些命名空间提供的部分属性:

System.ComponentModel.DataAnnotations.Schema System.ComponentModel.DataAnnotations

似乎只有 RequiredMaxLength 适合您的情况。检查这个 -> EF Core Annotations

其余属性可用于 ASP.NET Core API 中的模型验证 --> Click

【讨论】:

  • 正确。这个列表确实应该由官方 EF Core 文档而不是外部来源提供,但既然他们没有,那也没关系。
  • 我同意,这样的东西不只是放在一个地方,这真的让我感到厌烦。他们甚至have page用例子来解释用法,我想用一行解释的表格不会对他们造成太大的伤害吧?
猜你喜欢
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 2014-01-20
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 2013-05-30
相关资源
最近更新 更多