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 of all, I'm new to MVC.

ProjectID, ProjectNumber, and ProjectDescription columns may be found in my project table. The ProjectNumber must meet the requirement of being unique, and the ProjectId is an entityKey of type int.

In entity framework 6.1.3, how do I go about doing this?

I have a project in my class.

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

The column is not configured as unique in the database when I construct the database from the model.

Why am I misusing this?

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

Popular Answer

Considering the response in coding for Entity Framework's first distinct column

Attempt this code:

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

Additionally, check that the string in your SQL Server is not set to nvarchar(MAX) else Entity Framework Code First will fail.

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