添加唯一约束目前网上都是 EF5及以上的内容了,新技术肯定强,一个特性就解决了
//EF5以下版本并不支持
[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public string Email { get; set; }
老框架找了半天,现在搬运一下
class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasIndex(p => new { p.FirstName, p.LastName })
.IsUnique(true);
}
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
还有另一种写法:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>(entity => {
entity.HasIndex(e => e.Email).IsUnique();
});
}