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

asp.net-mvc c# ef-database-first entity-framework entity-framework-6

Question

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?

1
4
9/14/2016 8:14:26 AM

Popular Answer

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.

3
5/23/2017 12:08:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow