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.
ntext, which is effectively an unbounded string, and can't be indexed. In sql server, at-least, there's a limit of ~900 bytes on an indexed field, and only certain types can be indexed. You'd probably want to go for annvarchar(450)(or shorter, if you can afford). I believe there are attributes that can help here.[StringLength(450)]will do the trick.Nameis truly unique then it could be the primary key which would be a natural key and you wouldn't need theIdcolumn unless it has some real life meaning (many people just slap Id columns on all their tables).