How to configure One to Many relationship in Entity Framework

Viewed 455

I am creating API in ASP .NET Core that will retrieve posts with user Id. Post should contain text and Id of a user who posted it.

I have two models Users and Posts and I need help on how to configure this relationship

I want one User to have many posts

Currently my user model contains

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }

    public List<Post> Posts { get; set; }
}

And my Post model

public class Post
{
    public int Id { get; set; }
    public string Text { get; set; }
}

What is the best way to do this ?

2 Answers

One to many relationships ( User to have many posts).

public class User{

public int Id { get; set; }
public string Username { get; set; }
public List<Post> Posts { get; set; }

}
public class Post
{
    public int Id { get; set; }

    public string Text { get; set; }

    //Navigation
    public int UserId { get; set; }

    public User User{ get; set; }
    
}

this is your Model Class:

public class User
{
      public int Id { get; set; }
      public string Username { get; set; }
      public Virtual List<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }

    public string Text { get; set; }
    
    public int UserId { get; set; }
     
    public Virtual User User { get; set; }

}

and in your DbContext:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // configures one-to-many relationship
        modelBuilder.Entity<User>().HasMany(x=>x.Posts).WithRequired(x=>x.User)
            .HasForeignKey<int>(s => s.UserId);

    }
Related