Home > Back-end >  ASP.NET Entity Framework InMemory database not saving related sub-entities
ASP.NET Entity Framework InMemory database not saving related sub-entities

Time:09-20

I have an ASP.NET project in which I tried using an in-memory database to save weather objects.

The Weather class contains another object, Location. At startup of the application, I generate data and save it to my database context. However, when sending a get request, all weather attributes work except for location, that value is null every time.

Relevant code:

Weather

public class Weather
{
    public int Id { get; private set; }
    public Variable WeatherVariable { get; set; }
    public Unit WeatherUnit { get; set; }
    public Location WeatherLocation { get; set; }
}

Location

public class Location
{
    public int Id { get; private set; }
    public long LocationCode { get; set; }
    public string LocationName { get; set; }
}

At the start of the app, this code is run to add data to the in memory database:

using (var context = new WeatherContext(
           serviceProvider.GetRequiredService<DbContextOptions<WeatherContext>>()))
{
    // Look for any Weather objects.
    if (context.Weathers.Any())
    {
        return; // Data was already seeded
    }
    
    string[] weatherLocations = {
        "Utrecht", "Amersfoort", "Amsterdam", "Langerak", "Putten", "Rotterdam", "Den Haag", "Aken"
    };

    context.Weathers.AddRange(
            Enumerable.Range(1, 5).Select(index => new Weather
            {
                WeatherLocation = new Location
                {
                    LocationCode = Random.Shared.Next(1000, 7000),
                    LocationName = weatherLocations[Random.Shared.Next(weatherLocations.Length)]
                },
                WeatherUnit = Unit.CELSIUS,
                WeatherVariable = Variable.TEMPERATURE
            }).ToList());
    
    // I already tried this from a different stackoverflow question, but didn't work for me.
    context.Weathers.Include(w => w.WeatherLocation);
    
    context.SaveChanges();
}

And then here is the controller:

[HttpGet]
public List<Weather> GetWeathers()
{
    _context.Weathers.Include(location => location.WeatherLocation);
    return _context.Weathers.ToList();
}

I tried multiple solutions already. But whatever I do, the sub entity (Location) stays null:

Screenshot of API response

CodePudding user response:

Thanks to the help in the comments, I found what works for me:

Adding this method to my WeatherContext class solved Location not loading:

// This is so that the Weather objects automatically include location upon loading.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Weather>().Navigation(w => w.WeatherLocation).AutoInclude();
}
  • Related