我有两个班级联系人和小组
组合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; }
}
Run Code Online (Sandbox Code Playgroud)
检查重复项意味着您必须转到数据库进行验证.在实体框架代码中,这意味着使用DbContext.有关如何在Entity Framework中进行验证的详细说明,请参阅使用ValidateEntity在Context中实现验证.
您应该覆盖上下文类中的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"));
}
Run Code Online (Sandbox Code Playgroud)
当有人打电话时会触发此验证SaveChanges.如果有任何错误,DbEntityValidationException则抛出a.
更多关于结构化验证的信息
对于"带和括号"方法,我还在我的自然键上为数据库添加了唯一索引 - 在迁移中.因此,由于不通过实体框架插入数据库而阻止了无效数据:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
更多关于索引的信息
附加说明 从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; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5142 次 |
| 最近记录: |