C
C#2y ago
:

Foreign key to Asp.net user

I am currently making a model class and for one of the fields I would like to make a foreign key referencing to the id of a user in the asp.net user table, but I am not sure how and have tried to look on google.
10 Replies
Angius
Angius2y ago
Just do
public MyCoolUser User { get; set; }
public TKey UserId { get; set; }
public MyCoolUser User { get; set; }
public TKey UserId { get; set; }
This will be easiest, using a navigation property and the ...Id convention to tell EF this property stores the ID (TKey being the type of the key, ofc)
:
:OP2y ago
Yeah but the user table is autocreated by asp.net so Im not sure what type mycooluser is
Angius
Angius2y ago
So? Ah IdentityUser
:
:OP2y ago
Oh I see
Angius
Angius2y ago
And the ID type will be string, I believe
:
:OP2y ago
alright I think I got it then thanks
[ForeignKey("UserId")]
public string AuthorId { get; set; }

public IdentityUser User { get; set; }
[ForeignKey("UserId")]
public string AuthorId { get; set; }

public IdentityUser User { get; set; }
should be this right?
Angius
Angius2y ago
Or just name your nav property Author and get rid of the attribute If you have a property Foo, then a property FooId will be automatically set to store the foreign key No need for any additional config
:
:OP2y ago
Oh I see thanks
public string LastEditedBy { get; set; }

public IdentityUser User2 { get; set; }
public string LastEditedBy { get; set; }

public IdentityUser User2 { get; set; }
will this work if I need a second fk to the same table since I cant use User again
Angius
Angius2y ago
public string LastEditedById { get; set; }

public IdentityUser LastEditedBy { get; set; }
public string LastEditedById { get; set; }

public IdentityUser LastEditedBy { get; set; }
:
:OP2y ago
bet, thanks
Want results from more Discord servers?
Add your server