1

I have an entity like this:

public class User
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }   // this is an EmailAddress

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

How can I define the Username to be unique too?

Using Entity Framework 6.1.3

Felix D.
  • 4,811
  • 8
  • 38
  • 72

1 Answers1

3

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

Community
  • 1
  • 1
Ivan Yurchenko
  • 3,762
  • 1
  • 21
  • 35