How to create a foreign key pointing to the db table created by ASP.NET Identity (AspNetUsers)?
Hi! I'm making a house listings app for school, using the MVC pattern. Naturally, one of my main db tables is "HouseListings" and naturally one of the columns on that table is UserId and it's supposed to be based on a foreign key pointing to a user ID to associate that particular House Listing to the user that created it. What I wanted to do was avoid creating my own "Users" db table on top of the built in "AspNetUsers" one created automatically when I accepted the Identity schema, so I need to point to that in my HouseListings model class, but obviously AspNetUsers isn't in my Model. From my googling it seems that one can actually bring the Identity models explicitly into my project and work from there, but I don't think that would be necessary. Can I just do a dummy empty class in my Model? Like so:
Thus "bringing in" the AspNetUsers table into my Model and that way I can point to it in my "HouseListings" model class. Would this work? If not how can I make it work to do what I said?
9 Replies
You can just create a navigation property to
IdentityUser
That said, inheriting from IdentityUser
is something you'll have to do anyway, soon as you want to put anything else on the userOk, so to make sure I understand. I now have this class in my project:
and in my HouseListings class, I now have:
Why?
Scratch that
IdentityOwner
, it seems useless
Just have
The foreign key decoration is necessary tho right?
Not at all
By convention,
[Name]Id
property is the foreign key to the table represented by [Name]
propertyThen in your example, UserId is pointing to the Id of a User class I also have to have? Or just the User object created immediately below it?
There's no
User
class in my example
Nor does the property create any objects
IdentityUser
is the base user type used by Identity
This property references it
Thus, creating a one-to-* relationshipand by convention UserId will automatically point to the Users table created by Identity??
You would have to configure the exact relationship kind
UserId
will store the foreign key