Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 342
amdorsey12 Avatar asked Oct 20 '25 09:10

amdorsey12


1 Answers

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.

like image 85
FireAlkazar Avatar answered Oct 21 '25 21:10

FireAlkazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!