Dmitriy Gavrilenko Dmitriy Gavrilenko - 1 month ago 10
C# Question

Entity Framework Core does not save related data

In continuation of yesterday's post

Two Entities

public class Realtor
{
public Realtor()
{
Guid = Guid.NewGuid();
Registration = DateTime.Now;
}
public int Id { get; set; }
public Guid Guid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Registration { get; set; }
public int SubdivId { get; set; }
public Subdiv Subdiv { get; set; }
}

public class Subdiv
{
public Subdiv()
{
Created = DateTime.Now;
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public List<Realtor> Realtors { get; set; }
}


I spend test


  1. I added one Subdiv (TOSTER TM) and received his ID

  2. Next, I add a Realtor and I push Subdiv property found on the ID, the newly created TOSTER TM
    Realtor.Subdiv is an object of type Subdiv. OK.
    enter image description here

  3. Then I try to select from the base the newly added Realtor.
    Realtor.Subdiv = null
    OMG!!
    enter image description here

  4. We get Subdiv object, which is lacking in Realtor above and see his
    List<Realtor> = null



enter image description here

Please help in solving this problem.

Answer

The problem is not with saving the related data (it should be saved correctly, you could check that inside the database), but loading it.

EF Core currently does not support lazy loading, so in order to get the related data you need to explicitly request it (the so called eager loading):

Realtor rl = context.Realtors.Include(r => r.Subdiv).First(r => r.Id == id);

For more info, see EF Core: Loading Related Data.