2016-12-20 14 views
22

nie mogę znaleźć sposób, aby dodać unikalny ograniczenie do mojego atrybutu polaEntity Framework rdzenia dodać UNIQUE Kod pierwszego

public class User 
{ 
    [Required] 
    public int Id { get; set; } 

    [Required] 
    // [Index("IX_FirstAndSecond", 2, IsUnique = true)] not supported by core 
    public string Email { get; set; } 

    [Required] 
    public string Password { get; set; } 
} 

Używam

"Microsoft.EntityFrameworkCore": "1.0.1", 
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1", 
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1", 
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", 
+0

Próbki biegle API dla indeksów zobaczyć na https://www.learnentityframeworkcore.com/configuration/fluent-api/hasindex-metho d –

Odpowiedz

53

Na EF rdzenia nie można utworzyć Indeksy wykorzystujące adnotacje danych. Ale możesz to zrobić za pomocą Fluent API.

Jak to wewnątrz {} Db Context.cs:

protected override void OnModelCreating(ModelBuilder builder) 
    { 
     builder.Entity<User>() 
      .HasIndex(u => u.Email) 
      .IsUnique(); 
    } 

Możesz przeczytać więcej na ten temat tutaj: Indexes

+1

Bardzo dziękuję za pomoc, to właściwe rozwiązanie! –

+0

Serdecznie witamy :) – Sampath

11

Także jeśli chcesz stworzyć niepowtarzalne ogranicza na wielu kolumnach można po prostu zrobić ten (po @ Sampath za link)

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; } 
} 
Powiązane problemy