EF Core 3 - One-To-Many Relationship is not populating

asp.net-core c# entity-framework-core

Question

I've got 2 models - User and Order. A User has many orders and a order has one user.

public class User
{
    [Key]
    public int Id { get; set; }

    ...

    public List<Order> Orders { get; set; } = new List<Order>();
}
public class Order
{
    [Key]
    public int Id { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }

    ...
}

My database provider is MySQL, so I'm using Pomelo.EntityFrameworkCore.MySql.

The problem is that the Orders property is always empty (or null without the property initializer). I've tried playing around with ForeignKey and InversionProperty, but it doesn't help.

Any help is appreciated.

1
0
4/16/2020 12:46:28 PM

Accepted Answer

In order to have the Order.User and User.Orders populated you need to call .Include(). For example:

this.databaseContext.Orders.Include(order => order.User).Where(...);
this.databaseContext.Users.Include(user => user.Orders).Where(...);

Source: https://docs.microsoft.com/en-us/ef/core/querying/related-data

Edit: As seeing the comments under the question I think you have problem with setting up the relation between the two classes. In your context you should setup the relations. Here is an example:

protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Entity<Order>()
        .HasOne(_ => _.User)
        .WithMany(_ => _.Orders)
        .HasForeignKey(_ => _.UserId);
}

Source: https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

1
4/16/2020 1:00:34 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow