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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

ty will try that immediately :D
I am getting this exception: "Column 'Username' in table 'dbo.Users' is of a type that is invalid for use as a key column in an index."
it seems to correspond to stackoverflow.com/a/23055838/4610605 can you help me out ? I don't get whats wrong ....
Try to add the MaxLength attribute. The Indexes length is limited so you have to specify the max length value for your property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.