0

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; }
}
9
  • Please can you tel us if you use CodeFirst or BaseFirst ? It's will help. Commented Apr 12, 2018 at 12:28
  • You don't need to. You already have ApplicationUser in the Post table. For example; if you want to see all Posts by a particular user, you simply call context.Posts.Where(p => p.User.Id == 5) Commented Apr 12, 2018 at 15:49
  • @Cedric code first , Commented Apr 12, 2018 at 15:55
  • @AdamVincent i agree with you , but i want insert UserId as foreign key in Post table ? Commented Apr 12, 2018 at 15:56
  • Then instead of public ApplicationUser User { get; set; } change it to public int ApplicationUserId { get; set; } .. I say instead because if you have both, then it would be redundant. Then you will need to do some additional Fluent API code to map the foreign key to the User table. If you keep it as is, EF does all the work for you without any additional overhead. Commented Apr 12, 2018 at 15:59

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.