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


I'm attempting the following:

To prevent someone from applying to the same posting more than once, add the UNIQUE constraint IX Unique Applicatation as a business rule to the Application Class.

I'm attempting to use 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; }


I receive the following when I add-migrate IX Unique Applicatation:

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

        public override void Down()

It is entirely empty (obviously, there should be something in the void Up and void Down). I've experimented with it in a few other sectors. I don't know where I'm going wrong, so any assistance would be highly appreciated.

I've tried using this kind of code, however it keeps giving me an issue regarding my Unique on the ID column.

[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

You can attempt this even though I'm not sure how to use data annotations for it.

As part of 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