Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Data Model with ApplicationUser Field as Foreign Key and Populating This With the User ID

$
0
0

Hello

I have created my first ASP.NET Core web application using the individual user accounts option and added a new data model (for blog entries) where I want to add a CreatedBy field to store the ID of the logged in user.

This is the field I added:

public ApplicationUser ApplicationUser { get; set; }

I then ran the command to generate edit pages for this data model:

dotnet aspnet-codegenerator razorpage -m Blog -dc ApplicationDbContext -udl -outDir Pages\Blogs2 --referenceScriptLibraries

I hoped the user ID might save to the field automatically but it didn't. So in the OnPostAsync() method I have tried to set the value for this field but whatever I try, the user ID ends up as a string and I get an error that string cannot be converted to ApplicationUser.

I did manage to add a string column and populate this with the user name of the logged in user on save but then this means the data model doesn't link on the primary key.

Please can someone tell me the correct way to store the User ID in a field in another table as a foreign key.

I have spent hours trying various techniques on the internet and they are either written for .NET Core 1 or .NET (non-core) so don't work.

Thanks

Robin


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>