Nudity Nudity - 5 months ago 27
SQL Question

Entity framework - Columns with unique values

I have a Entity like this:

public class User
{
public string Name { get; set; }

public string LastName { get; set; }

public string Username { get; set; } //this is an EmailAdress

[Key]
public Guid Id { get; set; }
}


how can I define the Username to be unique too ?

I cannot set it as a second Key...

Entity Framework 6.1.3

Answer

If you’re using the newest EF (6.1+) then you can use this code:

[Index("UserNameIndex", IsUnique = true)]
[MaxLength(100)]
 public string UserName { get; set; }

With EF of earlier versions there’s more complex approach which you can check here: Unique key with EF code first

Comments