Search code examples
razorasp.net-mvc-5

Unique key applying on asp.net MVC 5 model property


I have User(name,password) model and Roles model(id,role).Now what I want is mapping model(id,Uid,Rid) between these two models and here Uid,Rid foreign keys also Uid should be unique. How can acheive this. I have done with foreign key and with mapping table but I stuck at unique key applying on Uid.

Can anyone help me in this? Thanks in advance.

 public class Image
 {
    public int id { get; set; }

    public string Name{ get; set; }

    public String Password { get; set; }
}

//User roles class
public class Role
{
    public int id { get; set; }

    public string Roles { get; set; }
}

//User mapping with roles
public class Rolemapping
{
    public int id { get; set; }

    public int Uid { get; set; }

    [ForeignKey("Uid")]
    public Image User { get; set; }

    public int Rid { get; set; }

    [ForeignKey("Rid")]
    public Role Role { get; set; }
}

Solution

  • Unique Key in Model Code First

    Follow the above link to create Unique Key prior to EF 6.1 and

    EF 6.1 onwards you can easily have unique constrains ,

    [Index("TitleIndex", IsUnique = true)]

    public string Title { get; set; }