EF 6 IsRequired() allowing empty strings

半世苍凉 提交于 2019-12-05 12:26:04

问题


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 current project utilizng EF6, The DBEntityValidationException is not thrown when the string property is empty.

Entity:

public class Application : BaseEntity
{
    public string Name { get; set; }

    // navigation properties
    public IList<Role> Roles { get; set; }
}

Configuration:

internal class ApplicationMapping : EntityTypeConfiguration<Application>
{
    public ApplicationMapping()
    {
        // table name
        this.ToTable("Applications");

        // properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(100);
    }
}

After pouring over the MSDN EF documentation and stack overflow, I am at a loss for why this is happening. Did a convention get added/modified to EF6?


回答1:


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

[Required(AllowEmptyStrings = false)]

False is default




回答2:


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.




回答3:


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; }


来源:https://stackoverflow.com/questions/20619632/ef-6-isrequired-allowing-empty-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!