none
How to create ForeignKey reference to code-first identity tables. RRS feed

  • Question

  • Hi,

    I'm developing a web application using MVC 5, EntityFramework 6 with a Code-First approach.

    I have successfully created my tables dbo.AspNetRoles, dbo.AspNetUsers... etc, also I have created some custom tables for example a table that must have a relationship between the menus presented and the role of the authenticated user. What I want to add to my model is a property like this:

    [ForeignKey]

    public virtual AspNetRoles Roles { get; set; }

    But of course I have not an AspNetRoles class, because the framework auto generates the tables only in the SQL database, so my question is, I have to manually create this classes? How can I link them to the database tables, I think the issue may be deeper. If I can't do this maybe I should go back to SQL manual queries.

    Thanks!
    Thursday, April 23, 2015 6:43 PM

Answers

  • Hello Morral,

    >> What I want to add to my model is a property like this:

    If you have a separate model to store your own business model, what you have written should be almost ok, however, please take care the [ForeignKey] attribute is usually used to markup a property as an integer property to specify it as a foreign key:

    public virtual int RoleID { get; set; }

     [ForeignKey("RoleID")]  public virtual AspNetRoles Roles { get; set; }

    Or it would generated a combinatorial name.

    >> But of course I have not an AspNetRoles class, because the framework auto generates the tables only in the SQL database, so my question is, I have to manually create this classes?

    From your description, the AspNetRoles class seems to be a system class which is not exposed to user. If so, these classes already exists, you do not need to create them again.

    I notice that you are working with the MVC project, you could also ask this issue to the MVC forum: http://forums.asp.net/1146.aspx

    There are MVC experts will help you.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, April 24, 2015 7:54 AM
    Moderator