Search code examples
c#asp.net-coreentity-framework-corein-memory-database

EF Core In Memory Database not saving ICollection object column


I have read that InMemory Database with EF Core has limitations and was considering moving to sqlite for development, however, I wanted to know if this behavior is a limitation of InMemory Database or if it's me. I have tried reading the documentation but can't find material explicitly mentioning this. I have the following:

    // Startup
    services.AddDbContext<StudentResultsContext>(opt =>
                                               opt.UseInMemoryDatabase("StudentResultsList"));
    // context
    public class StudentResultsContext : DbContext
    {
        public StudentResultsContext(DbContextOptions<StudentResultsContext> options)
            : base(options)
        {
        }

        public DbSet<StudentResults> StudentResultsList { get; set; }
    }

    // classes
    public class StudentResults
    {
        public long ID { get; set; }
        public long ParentId { get; set; }
        public string Name { get; set; }
        public ICollection<ExamScores> Results { get; set; }
    }

    public class ExamScores
    {
        public long ID{ get; set; }
        public long StudentId { get; set; }
        public Exam ExamType { get; set; }
        
        public double Score { get; set; }
    }
    // controller
    [HttpPost]
    public async Task<ActionResult<StudentResults>> PostStudentResults(StudentResults studentResults)
    {
        _context.StudentResultsList.Add(studentResults);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetStudentResults), new { id = studentResults.ID }, studentResults);
    }

Results is saved as null in the database up even though the return from post claims they were created, like so

The post enter image description here

What comes back from get enter image description here

Is this something I did or a problem with InMemory Databse?


Solution

  • I guess you don't do anything to load related data and thus you get null for Results.

    Try to get saved entity with context.StudentResultsList.Include(s => s.Results).

    Check Loading Related Data for other strategies.