Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a unique constraint on a field of type string in EF 6?

First, I am new to MVC.

I have a Project table which has ProjectID, ProjectNumber, and ProjectDescription fields. The ProjectId is an entityKey of type int, the ProjectNumber needs to be a unique constraint.

How do I do this in entity framework 6.1.3?

in my Project class I have

        public int ProjectID { get; set; }
        [Index(IsUnique = true)]
        [StringLength(200)]
        public string ProjectNumber { get; set; }
        public string ProjectDescription { get; set; }

when I generate database from model, the field is not set as unique in the database.

what am I doing wrong?

like image 996
user3726459 Avatar asked Sep 14 '16 01:09

user3726459


1 Answers

Based on the answer in Entity Framework code first unique column

Try this code:

public int ProjectID { get; set; }
[Index("ProjectNumber_Index", IsUnique = true)]
[MaxLength(200)]
public string ProjectNumber { get; set; }
public string ProjectDescription { get; set; }

And make sure the string is not set to nvarchar(MAX) in your SQL Server or you will see an error with Entity Framework Code First.

like image 118
Keyur PATEL Avatar answered Nov 12 '22 10:11

Keyur PATEL