我有两个班级联系人和小组
FirstName
和LastName
的组合必须是唯一的,并且可以为单个联系人添加多个地址。我如何才能在实体框架代码第一种方法中做到这一点?
public class Contacts
{
[Key]
public int ContactID { get; set; }
[ForeignKey("Group")]
public int GroupID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Number { get; set; }
[Required]
[EmailAddress]
public string EmailId { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public virtual Groups Group { get; set; }
}
public class Groups
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GroupID { get; set; }
[Required]
public string GroupName { get; set; }
[Required]
public string GroupDiscription { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
答案 0 :(得分:5)
检查重复项意味着您必须前往数据库进行验证。在实体框架代码中,这意味着使用DbContext。有关如何在Entity Framework中进行验证的详细说明,请参阅Implementing Validation in the Context with 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
。
有关结构化验证的更多信息here
对于“腰带和括号”方法,我还在我的自然键上为数据库添加了唯一索引 - 在迁移中。因此,由于不通过实体框架插入数据库而阻止了无效数据:
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");
}
}
有关索引here
的更多信息附加说明 从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; }
答案 1 :(得分:1)
实体框架中没有对此的神奇支持。您必须手动执行此操作。首先检查一批中的联系人是否具有唯一的名称。然后检查数据库中是否存在任何FirstName/LastName
组合。
但这永远不会成为一个强大的解决方案,因为在检查和最终提交数据库之间总会存在延迟。因此,作为终极防守,你真的应该在FirstName/LastName
上添加一个独特的数据库索引。