EF 6 IsRequired()允许空字符串

时间:2013-12-16 19:50:24

标签: entity-framework entity-framework-6

在以前使用EF5和EF4版本的项目中,如果属性为null或为空字符串,则IsRequired()流畅的API方法将抛出DbEntityValidationException。在我当前的项目utilizng EF6中,当字符串属性为空时,不会抛出DBEntityValidationException。

实体:

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

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

配置:

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

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

在倾注了MSDN EF文档和堆栈溢出之后,我不知道为什么会发生这种情况。是否已将约定添加/修改为EF6?

3 个答案:

答案 0 :(得分:22)

现在,您仍然可以使用[Required]属性,并且可以配置AllowEmptyStrings

[Required(AllowEmptyStrings = false)]

默认是

答案 1 :(得分:16)

您可能会混淆StringColumnConfiguration.IsRequired MethodRequiredAttribute

.IsRequired()标记数据库中的列为NOT NULL。但是,如果属性为null,包含空字符串(“”)或仅包含空格字符,[Required]注释将引发验证异常。

答案 2 :(得分:0)

此处是EF Core 2.1-看起来像使用[Required]将属性标记为必需属性,然后使用空字符串值将其保存到数据库中,让它经历了...很奇怪。

文档规定以下内容:

//
// 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; }
相关问题