Search code examples
entity-frameworkdata-annotationsentity-framework-4.3

Entity Framework code first unique column


I am using Entity Framework 4.3 and using Code Fist.

I have a class

public class User
{
   public int UserId{get;set;}
   public string UserName{get;set;}
}

How do I tell Entity Framework that UserName has to be unique when creating database table? I would prefer to use data anotations instead of configuration file if possible.


Solution

  • Solution for EF4.3

    Unique UserName

    Add data annotation over column as:

     [Index(IsUnique = true)]
     [MaxLength(255)] // for code-first implementations
     public string UserName{get;set;}
    

    Unique ID , I have added decoration [Key] over my column and done. Same solution as described here: https://msdn.microsoft.com/en-gb/data/jj591583.aspx

    IE:

    [Key]
    public int UserId{get;set;}
    

    Alternative answers

    using data annotation

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("UserId")]
    

    using mapping

      mb.Entity<User>()
                .HasKey(i => i.UserId);
            mb.User<User>()
              .Property(i => i.UserId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
              .HasColumnName("UserId");