【发布时间】:2013-12-16 19:50:24
【问题描述】:
在过去使用 EF5 和 EF4 版本的项目中,如果属性为 null 或空字符串,IsRequired() fluent API 方法将引发 DbEntityValidationException。在我当前使用 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 添加/修改了约定?
【问题讨论】:
-
你在
OnModelCreated方法里面注册了你的EntityTypeConfiguration吗?所以modelBuilder.Configurations.Add(new ApplicationMapping ()); -
是的,我已经验证了实体类型配置是在创建模型时实例化的。 IsRequired() 在 Name 属性为 null 时抛出 DBEntityValidationException,但在 Name = string.Empty 时不抛出
标签: entity-framework entity-framework-6