Create unique attribute beyond the Primary Key in code-first

4

I am creating a Logradouro table where the CEP field is not the primary key, but must be unique. How do I do this using code-first in Entity 6.0 ?

To create primary key I use the HasKey method:

ToTable("Logradouros").HasKey(x => x.LogradouroId);

I saw that in this method you can use more than one field by creating composite key. If CEP needs to be unique and indexed should it be table key too?

    
asked by anonymous 16.06.2016 / 21:27

1 answer

3

You can use [Index]

[Index(IsUnique = true)] 
[StringLength(200)] 
public string Username { get; set; } 

link

If you are using modelBuilder, use the following:

modelBuilder.Entity<User>()
    .HasIndex("IX_Username",          // Provide the index name.
        e => e.Property(x => x.Username))  // Multiple columns as desired.

link

    
16.06.2016 / 21:36