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