检查重复项意味着您必须去数据库进行验证。在 Entity Framework Code First 中,这意味着使用 DbContext。有关如何在 Entity Framework 中进行验证的详细说明,请参阅使用 ValidateEntity 在上下文中实现验证。
您应该在上下文类中覆盖 ValidateEntity 方法:
protected override DbEntityValidationResult ValidateEntity(
DbEntityEntry entityEntry,
IDictionary<object, object> items)
{
//base validation for Data Annotations, IValidatableObject
var result = base.ValidateEntity(entityEntry, items);
//You can choose to bail out before custom validation
//if (result.IsValid)
// return result;
CustomValidate(result);
return result;
}
private void CustomValidate(DbEntityValidationResult result)
{
ValidateContacts(result);
ValidateOrganisation(result);
}
private void ValidateContacts(DbEntityValidationResult result)
{
var c = result.Entry.Entity as Contact;
if (c== null)
return;
if (Contacts.Any(a => a.FirstName == c.FirstName
&& a.LastName == c.LastName
&& a.ID != c.ID))
result.ValidationErrors.Add(
new DbValidationError("Name",
"Name already exists"));
}
private void ValidateOrganisation(DbEntityValidationResult result)
{
var organisation = result.Entry.Entity as Organisation;
if (organisation == null)
return;
if (Organisations.Any(o => o.Name == organisation.Name
&& o.ID != organisation.ID))
result.ValidationErrors.Add(
new DbValidationError("Name",
"Name already exists"));
}
当调用 时会触发此验证SaveChanges
。如果有任何错误,DbEntityValidationException
则抛出 a。
更多关于结构验证的信息在这里
对于“带和大括号”方法,我还在我的自然键上向数据库添加唯一索引 - 在迁移中。从而防止由于不通过 Entity Framework 向数据库中插入而导致的无效数据:
public partial class Adduniqueindexes : DbMigration
{
public override void Up()
{
//You have to use Sql if the column is nullable:
Sql(@"CREATE UNIQUE INDEX IX_UPRN ON Properties(UPRN, OrganisationID)
WHERE UPRN IS NOT NULL"));
CreateIndex("dbo.Organisations",
"Name",
unique: true,
name: "IX_NaturalKey");
CreateIndex("dbo.Contacts",
new string[] { "FirstName", "LastName" },
unique: true,
name: "IX_NaturalKey");
}
public override void Down()
{
DropIndex("dbo.Properties", "IX_UPRN");
DropIndex("dbo.Organisations", "IX_NaturalKey");
DropIndex("dbo.Contacts", "IX_NaturalKey");
}
}
更多关于索引的信息在这里
附加说明
从 EF6.1 开始,可以通过添加数据属性来指示应在字段上创建索引:
[Index("IX_NaturalKey", IsUnique = true)]
[Required] //If the field is nullable then you have to create the index in the migration
//using sql, so I'd only expect IsUnique = true on a Required field
[StringLength(256)] //indexes must be less than 900 bytes in Sql Server,
//so nvarchar(max) will not do
public string Name{ get; set; }