EF 6 IsRequired()允许空字符串

awo*_*ske 14 entity-framework entity-framework-6

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

实体:

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

    // navigation properties
    public IList<Role> Roles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

组态:

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

        // properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(100);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Tod*_*odd 25

这些天你仍然可以使用[Required]属性并具有可配置性AllowEmptyStrings

[Required(AllowEmptyStrings = false)]
Run Code Online (Sandbox Code Playgroud)

假是默认的

  • 我不知道他们为什么会在空字符串上验证失败.将列标记为不可为空不应该禁止空字符串. (3认同)

cka*_*kal 17

您可能会混淆StringColumnConfiguration.IsRequired方法RequiredAttribute.

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