Unique key applying on asp.net MVC 5 model propert

2019-05-30 06:56发布

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; }
}

1条回答
不美不萌又怎样
2楼-- · 2019-05-30 07:25

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; }

查看更多
登录 后发表回答