Вопрос
Можно ли определить уникальное ограничение для свойства, используя либо свободный синтаксис, либо атрибут? Если нет, какие обходные пути?
У меня есть класс пользователя с первичным ключом, но я хотел бы убедиться, что адрес электронной почты также уникален. Возможно ли это без непосредственного редактирования базы данных?
Решение (на основе ответа Мэтта)
public class MyContext : DbContext {
public DbSet<User> Users { get; set; }
public override int SaveChanges() {
foreach (var item in ChangeTracker.Entries<IModel>())
item.Entity.Modified = DateTime.Now;
return base.SaveChanges();
}
public class Initializer : IDatabaseInitializer<MyContext> {
public void InitializeDatabase(MyContext context) {
if (context.Database.Exists() && !context.Database.CompatibleWithModel(false))
context.Database.Delete();
if (!context.Database.Exists()) {
context.Database.Create();
context.Database.ExecuteSqlCommand("alter table Users add constraint UniqueUserEmail unique (Email)");
}
}
}
}