为什么在未设置必需的关系属性时不会触发DbValidationException?

时间:2013-02-06 14:18:03

标签: entity-framework validation

我的模特:

public class Post
{
  public int PostId { get; set; }
  public string Name { get; set; }
  public string Content { get; set; }
  public int? BlogId { get; set; }
  public Blog Blog { get; set; }
}

public partial class PostMap : EntityTypeConfiguration<Post>
{
  public PostMap() : base()
  {
    HasKey(c => c.PostId);
    Property(c => c.Content);
    Property(c => c.Name).IsRequired();       
    HasRequired(m => m.Blog)
                      .WithMany(t => t.Posts)
                      .HasForeignKey(m => m.BlogId)
                      .WillCascadeOnDelete(false);
    ToTable("Post");
  }
}

第一个例子:

  using (var ctx = new BlogContext())
  {
    try
    {
      Post post = new Post { Content = "Content" };

      ctx.Posts.Add(post);

      ctx.SaveChanges(); // fired DbEntityValidationException "The Name field is required"
    }
    catch (Exception e) { }
  }

第二个例子:

  using (var ctx = new BlogContext())
  {
    try
    {
      Post post = new Post { Content = "Content", Name = "Name" };

      ctx.Posts.Add(post);

      ctx.SaveChanges(); // fired DbUpdateException "Cannot insert the value NULL into column 'BlogId', table 'EntityFramework.dbo.Post'; column does not allow nulls. INSERT fails."
    }
    catch (Exception e) { }
  }

在我看来,这是一个错误。为什么不像第一个例子中那样触发DbEntityValidationException但是触发了DbUpdateException?我需要获取DbEntityValidationException。我试图将[Required]属性放在BlogId属性中。然后我得到DbEntityValidationException,但我不想在Post类中使用属​​性。是否可以在不使用BlogId属性上方的Required属性的情况下获取DbEntityValidationException?

0 个答案:

没有答案