0

I want to create a table that is similar to the AspNetUserRoles table in my database that has these columns:

User_id
Role_id

These columns are related to the user and role tables

How can I create one using my model? I have tried it like this:

public class AspNetUserRolesExtendedDetails
{
    [Key]
    [Column(Order = 0)]
    public ApplicationUser UserId { get; set; }
    [Key]
    [Column(Order = 1)]
    public AspNetRolesExtendedDetails RoleId { get; set; }
}

But when I try to run migrations, this error appears:

AspNetUserRolesExtendedDetails: : EntityType 'AspNetUserRolesExtendedDetails' has no key defined. Define the key for this EntityType.
AspNetUserRolesExtendedDetails: EntityType: EntitySet 'AspNetUserRolesExtendedDetails' is based on type 'AspNetUserRolesExtendedDetails' that has no keys defined.

How can I create a table like this and what is the proper name for it?

EDIT:

When I update my model like this:

public class AspNetUserRolesExtendedDetails
{
    [Key]
    [Column(Order = 0)]
    [ForeignKey("AspNetUsers")]
    public ApplicationUser UserId { get; set; }
    [Key]
    [Column(Order = 1)]
    [ForeignKey("AspNetRolesExtendedDetails")]
    public AspNetRolesExtendedDetails RoleId { get; set; }
}

I get this error:

The ForeignKeyAttribute on property 'RoleId' on type 'App.Models.AspNetUserRolesExtendedDetails' is not valid. The foreign key name 'AspNetRolesExtendedDetails' was not found on the dependent type 'App.Models.AspNetUserRolesExtendedDetails'. The Name value should be a comma separated list of foreign key property names.

Update:

    [Key]
    [Column(Order = 0)]
    [ForeignKey("Id")]
    public String UserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    [Key]
    [Column(Order = 1)]
    [ForeignKey("Id")]
    public String RoleId { get; set; }
    public virtual AspNetRolesExtendedDetails AspNetRolesExtendedDetails { get; set; }

This is what I have now but I'm getting this error:

The ForeignKeyAttribute on property 'UserId' on type 'App.AspNetUserRolesExtendedDetails' is not valid. The navigation property 'Id' was not found on the dependent type 'App.Models.AspNetUserRolesExtendedDetails'. The Name value should be a valid navigation property name.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JianYA
  • 2,750
  • 8
  • 60
  • 136

1 Answers1

0

So I managed to find a solution. For some reason copying the Objects name directly worked for me.

public class AspNetUserRolesExtendedDetails
{
    [Key]
    [Column(Order = 0)]
    [ForeignKey("ApplicationUser")]
    public String UserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    [Key]
    [Column(Order = 1)]
    [ForeignKey("AspNetRolesExtendedDetails")]
    public String RoleId { get; set; }
    public virtual AspNetRolesExtendedDetails AspNetRolesExtendedDetails { get; set; }
}
JianYA
  • 2,750
  • 8
  • 60
  • 136