使用唯一约束的三种方式:
方式1 自定义唯一约束
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueAttribute : ValidationAttribute
{
public override Boolean IsValid(Object value)
{
//校验数据库是否存在当前Key
return true;
}
}
View Code
在Model类中使用
public class Email
{
[Key]
public int EmailID { get; set; }
public int PersonId { get; set; }
[Unique]
[Required]
[MaxLength(100)]
public string EmailAddress { get; set; }
public virtual bool IsDefault { get; set; }
public virtual Boolean IsApprovedForLogin { get; set; }
public virtual String ConfirmationToken { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
}
方式2 扩展DataBase
SetInitializer 使用Sql语句添加
public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
protected override void Seed(MyContext context)
{
context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Categories (Title)");
}
}
在DbContext中使用
Database.SetInitializer(new MyInitializer());
方式3 使用Index特性
public class Email
{
[Key]
public int EmailID { get; set; }
public int PersonId { get; set; }
[Index("EmailAddress_Index", IsUnique = true)]
[Required]
[MaxLength(100)]
public string EmailAddress { get; set; }
public virtual bool IsDefault { get; set; }
public virtual Boolean IsApprovedForLogin { get; set; }
public virtual String ConfirmationToken { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
}