Skip to content

Saving objects containing Complex Types does not work #42

@hal-la

Description

@hal-la

Issue:

Complex Types are not saved with a FileBaseContext db. The issue happens when the Complex Type is mapped as a reference type or a value type (when explicitly mapped as a Complex Type).

The workaround that I accidentally stumbled upon while playing around with the Color class is to change the actual data type of the Complex type from a class to a struct, then removing the ComplexProperty mapping,

Model Setup:

   // This is the Complex Type
    public class ProfilePicture
    {
        public string Url { get; set; }
        public uint Height { get; set; }
        public uint Width { get; set; }
    }
    public class Player
    {
        public uint Id { get; private set; }
        public uint Level { get; set; }
        public ProfilePicture ProfilePicture { get; set; }
    }

DbContext Setup:

public class FileDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    private readonly string? _dbPath;

    public FileDbContext()
    {
        _dbPath = "local_db";
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseFileBaseContextDatabase(
                _dbPath,
                applyServices: services =>
                {
                    services.ConfigureJsonSerializerOptions(options =>
                    {
                        options.WriteIndented = true;
                    });
                }
            )
            .EnableSensitiveDataLogging();

        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Player>(e =>
        {
            e.ComplexProperty(pl => pl.ProfilePicture);
        });
    }
}

Test:

using (var db = new FileDbContext())
{
    Player player =
        new()
        {
            Level = 1,
            ProfilePicture = new ProfilePicture()
            {
                Url = "localhost/img.png",
                Height = 100,
                Width = 100
            }
        };
    db.Players.Add(player);
    db.SaveChanges();
}

Expected Result:

  {
    "Id": 1,
    "Level": 1,
    "ProfilePicture": {
      "Url": "localhost/img.png",
      "Height": 100,
      "Width": 100
    }
  }

Actual Result:

[
  {
    "Id": 1,
    "Level": 1
  }
]

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions