Search code examples
c#asp.netentityuniquedata-annotations

Entity Framework - Unique constraint on a string column


I'm a beginner with EF (6.2) and I'm trying to generate a database using the code first approach.

Some of my entities have a string property which should be unique, like the name of a user or the title of an article.

In order to ensure unicity, I've added an index which specifies that the column should be unique :

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Blog.Models
{
    public class User
    {
        [Key, Index, Required]
        public int Id { get; set; }

        [Index(IsUnique = true), Required]
        public string Name { get; set; }

        [Required]
        public string Password { get; set; }

        public ICollection<Comment> Comments { get; set; }
    }
}

However it complains because I'm trying to add an index on a string type column, while it accepts using an index on an integer column, such as the row ID.

I could use the Key attribute, but I'm already using it to define a primary key and I don't want EF to beleive that I want the name to be a component of a composite primary key nor to consider it as the actual primary key.

So my question is : Why can't I add an index on a column of string type and how can I ensure the unicity (uniqueness ?) of a given column ? Thank you.


Solution

  • As written in the Tutorial from MSDN, Indexes are possible on strings as they state in the following example code

    public class User
        {
            public int UserId { get; set; }
    
            [Index(IsUnique = true)]
            [StringLength(200)]
            public string Username { get; set; }
    
            public string DisplayName { get; set; }
        }
    

    but when it comes to Multiple-Column Indexes, they mention you need to write the order.

    Probably there's a conflict arising because you use Index without any name on Id, and also an Index without any name on Name. Try defining a name for the Index of the Name. I am not sure if this works, but it's worth a try.

    More info can be found here at the MSDN website.