How to set a unique constraint using Entity Framework Code First? entity-framework entity-framework-5 entity-framework-6


I'm trying to do the following:

In the Application Class: Add a UNIQUE constraint named IX_Unique_Applicatation as a business rule to make sure that no one can apply to the same posting more than once.

I'm trying to apply this to

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

namespace solution_MVC_HR.Models
    public class Application
        public int ID { get; set; }

        [Display(Name = "Covering Comments")]
        [Required(ErrorMessage = "You cannot leave the summary comments blank.")]
        [StringLength(2000,ErrorMessage ="Summary must be between 20 and 2000 characters",MinimumLength =20)]
        public string Comments { get; set; }

        [Required(ErrorMessage ="You must specify the job posting applied for.")]
        public int PostingID { get; set; }

        public virtual Posting Posting { get; set; }

        [Required(ErrorMessage = "You must specify the applicant applying to the job posting.")]
        public int ApplicantID { get; set; }

        [Index(IsUnique = true)]
        public virtual Applicant Applicant { get; set; }


When I Add-Migration IX_Unique_Applicatation I get:

public partial class IX_Unique_Applicatation : DbMigration
        public override void Up()

        public override void Down()

It's completely blank (obviously should have stuff in the void up and void Down I've tried it on a couple different fields..I don't see where I'm going wrong and would greatly appreciate the help.

edit: I've attempted this kind of coding with it giving me an error about my Unique on the ID field?

[Index("IX_MyTwoColumns", 1, IsUnique = true)]
public int UserAttributeId { get; set; }
public virtual UserAttribute UserAttribute { get; set; }
9/30/2017 2:40:43 AM

Popular Answer

I don't know doing this with data annotations, but you can try this.

In your DbContext class:

 protected override void OnModelCreating(ModelBuilder builder)
            .HasIndex(a => a.Applicant)
9/30/2017 6:44:21 PM

Related Questions


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