【发布时间】:2017-07-23 03:35:14
【问题描述】:
我想在保存上下文之前检查验证错误。 我调用 context.GetValidationErrors(),它是空的,然后我调用 context.SaveChanges(),我得到了我唯一索引的重复行的错误。
using(var context = new DefaultDbContext())
{
var user = new User()
{
OSIdentity = "test"
};
var duplicateUser = new User()
{
OSIdentity = "test"
};
context.Users.Add(user);
context.Users.Add(duplicateUser);
// this is empty
var errors = context.GetValidationErrors();
if(errors.Count == 0)
{
// this throws the exception for duplicate row for unique index "Idx_UserOSIdentity"
context.SaveChanges();
}
}
我的用户实体有以下列:
[Index("idx_UserOSIdentity", IsUnique = true)]
[Display(Name = "OSIdentity")]
[Required(AllowEmptyStrings = false, ErrorMessage = "...")]
[StringLength(450, ErrorMessage = "...")]
public string OSIdentity { get; set; }
为什么调用 context.GetValidationErrors() 时不检查唯一索引,但之后在 context.SaveChanges() 上抛出?
【问题讨论】:
标签: c# .net entity-framework validation entity-framework-6