Reputation:
Now I am building a mini blog. when user create a post I want to insert user id from AspNetUsers in post table as a foreign key here the post model, so can anyone tell me the steps to make it.
public class Post
{
[Required]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public string Path { get; set; }
[Required]
public DateTime PostDate { get; set; }
public ApplicationUser User { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
Upvotes: 0
Views: 1972
Reputation: 1
You have to use the below code to use AspNetUsersId
as a foreign key. You can use [Required]
if you don't want to make AspNetUsersId
as nullable.
public AspNetUsers User { get; set; }
[ForeignKey("AspNetUsersId")]
[Required]
public int AspNetUsersId { get; set; }
Yes, you have to manually set the AspNetUsersId
when you are inserting the record in Post
table.
Lets say you have object of class Post
as obj
. So you have to write the below code in your method, if AspNetUsers
table PK is Id
.
obj.AspNetUsersId = AspNetUsers.Id;
Upvotes: 1