2

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; }
}
madhu
  • 33
  • 2
  • 9

2 Answers2

3

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

Community
  • 1
  • 1
Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51
0

If you are using MYSQL you are likely to get BLOB/TEXT column 'value' used in key specification without a key length so add a key length

[Index("TitleIndex", IsUnique = true)]
[MaxLength(15)]
public string Title { get; set; }

This will change the field type to varchar as well

Diin
  • 565
  • 11
  • 41