我的模型:
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 ?