Créez d'abord la classe d'attributs personnalisés :
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueAttribute : ValidationAttribute
{
public override Boolean IsValid(Object value)
{
// constraint implemented on database
return true;
}
}
Puis ajoutez-les à vos classes :
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; }
}
Ajoutez ensuite un Initializer sur votre DbContext :
public class Initializer : IDatabaseInitializer<myEntities>
{
public void InitializeDatabase(myEntities context)
{
if (System.Diagnostics.Debugger.IsAttached && context.Database.Exists() && !context.Database.CompatibleWithModel(false))
{
context.Database.Delete();
}
if (!context.Database.Exists())
{
context.Database.Create();
var contextObject = context as System.Object;
var contextType = contextObject.GetType();
var properties = contextType.GetProperties();
System.Type t = null;
string tableName = null;
string fieldName = null;
foreach (var pi in properties)
{
if (pi.PropertyType.IsGenericType && pi.PropertyType.Name.Contains("DbSet"))
{
t = pi.PropertyType.GetGenericArguments()[0];
var mytableName = t.GetCustomAttributes(typeof(TableAttribute), true);
if (mytableName.Length > 0)
{
TableAttribute mytable = mytableName[0] as TableAttribute;
tableName = mytable.Name;
}
else
{
tableName = pi.Name;
}
foreach (var piEntity in t.GetProperties())
{
if (piEntity.GetCustomAttributes(typeof(UniqueAttribute), true).Length > 0)
{
fieldName = piEntity.Name;
context.Database.ExecuteSqlCommand("ALTER TABLE " + tableName + " ADD CONSTRAINT con_Unique_" + tableName + "_" + fieldName + " UNIQUE (" + fieldName + ")");
}
}
}
}
}
}
}
Enfin, ajoutez l'initialisateur à Application_Start dans Global.asax.cs
System.Data.Entity.Database.SetInitializer<MyApp.Models.DomainModels.myEntities>(new MyApp.Models.DomainModels.myEntities.Initializer());
C'est tout. En se basant sur le code vb à https://stackoverflow.com/a/7426773