EF 6 IsRequired() allowing empty strings

后端 未结 3 746
面向向阳花
面向向阳花 2021-02-12 17:14

In past projects with versions of EF5 and EF4, the IsRequired() fluent API method would thrown a DbEntityValidationException if the property was null or an empty string. In my

相关标签:
3条回答
  • 2021-02-12 18:02

    EF Core 2.1 here - looks like marking a property as required using [Required] and saving it to the DB with empty string value, let's it go through... very strange.

    Documentation states the following:

    //
    // Summary:
    //     Gets or sets a value that indicates whether an empty string is allowed.
    //
    // Returns:
    //     true if an empty string is allowed; otherwise, false. The default value is false.
    public bool AllowEmptyStrings { get; set; }
    
    0 讨论(0)
  • 2021-02-12 18:11

    You may be confusing the StringColumnConfiguration.IsRequired Method and RequiredAttribute.

    .IsRequired() marks that column in the database is NOT NULL. The [Required] annotation however, will raised a validation exception if the property is null, contains an empty string (""), or contains only white-space characters.

    0 讨论(0)
  • 2021-02-12 18:11

    These days you can still use [Required] attribute and have configurable AllowEmptyStrings

    [Required(AllowEmptyStrings = false)]
    

    False is default

    0 讨论(0)
提交回复
热议问题