Search code examples
c#.netin-memory-database

Nested Object cannot retain after posting when use InMemory database


I have 2 classes where one is nested in another like this

public class Account { 
    public int id {get; set;}
    public string Name {get; set;} 
    public AccountEntry Entry {get; set;} 
}

public class AccountEntry { 
   public int id {get; set;}
   public date date {get; set;}
   public string description {get; set;}
   public decimal hour {get; set;}
}

And use InMemory database like this:

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options.UseInMemoryDatabase("AccountDB");
}

It adds a record like this:

public void AddTimesheet(Account account)
{
     _context.Accouunts.Add(account);
     _context.SaveChanges();
}

And query like this:

public IList<Account> GetAllAccounts()
{    
    return _context.Accounts.ToList();
}

When first posting,it saves and the record can query correctly in same request. When post another input, all previous records' nested AccountEntry is null (Account.AccountEntry = null) but the immediate attribute like Name can retain. If it's a scope issue, the worker field should be lost too.

Why only the nested object lost?
Any way to fix it?


Solution

    1. AccountEntry is typeof(Input), but i suppose it is just a mistake in the question.
    2. EF loads related data (nested objects) lazily. So if you are only retrieving Account, related entities are not loaded. have you tried Include() ? https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager