Nudity Nudity - 1 year ago 90
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

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 Source

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

[Index("UserNameIndex", IsUnique = true)]
 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