Search code examples
c#sql-serverlistentity-framework-coresystem.text.json

How to transform "Types" a List<string> foo class property into a SQL Server table [Types](FooID int, name nvarchar) with Entity Framework Core


I received a JSON from a REST API, deserialized into a list of foo objects:

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public List<string> Types { get; set; }    // => those Types into a new SQL Server table (with each Id)
    ...
}

I'm using Entity Framework Core in my C# project. I would like to put my list of types into a new Types SQL Server table:

FooId Name
FooID 1 "type 1"
FooID 1 "type 2"
FooID 1 "type 3"
FooID 2 "type 2"
FooID 2 "type 3"
FooID 2 "type 4"

I tried to create a FooTypeConverter using System.Text.Json but I could not deal with the FooID in my read and write methods.

As well, with EF Core's ModelBuilder, I tried some code made from 365 copilot :

public class FooDbContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<FooType> FooTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure the primary key for Foo
        modelBuilder.Entity<Foo>()
            .HasKey(f => f.Id);

        // Configure the primary key for FooType
        modelBuilder.Entity<FooType>()
            .HasKey(ft => new { ft.FooId, ft.Type });

        // Configure the one-to-many relationship
        modelBuilder.Entity<Foo>()
            .HasMany(f => f.FooTypes)
            .WithOne(ft => ft.Foo)
            .HasForeignKey(ft => ft.FooId);

        // Configure the table names and column constraints
        modelBuilder.Entity<Foo>()
            .ToTable("Foos")
            .Property(f => f.Name)
            .HasMaxLength(50);

        modelBuilder.Entity<FooType>()
            .ToTable("FooTypes")
            .Property(ft => ft.Type)
            .HasMaxLength(100);
    }
}

but I'm pretty sure It won't work... I missed something.

Hasn't anyone tackled this problem before, I could not believe it!


Solution

  • I quickly solved the problem by coding an intermediate class "FooType". Sometimes you need to take a step back to find a solution that is quite simple.