How to seed data to a many-to-many link table in Entity Framework Core?

78 Views Asked by At

I have these two tables:

public class Resource  
{
    public int Id { get; set; }
    public string? NumberA { get; set; }
    public string? NumberB { get; set; }
    public ICollection<System> Systems { get; set; }
}

public class System
{
    public int Id { get; set; }
    public string? Code { get; set; }
    public string? Category { get; set; }
    public ICollection<Resource> Resources { get; set; }
}

Using EF Core creating migrations to the database, this creates a table called ResourceSystem with columns ResourcesId, SystemsId

Using the DbContext modelBuilder.Entity<>().HasData(), I can seed data to Resource and System tables. But in Visual Studio, I can not seed data to the "link table" ResourceSystem as it does not exists and I get the following error:

The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)

How do I seed data to such a many-to-many link table created by EF Core?

Update (v2):

modelBuilder.Entity<ResourceSystem>()UsingEntity(j => j
.HasData(new[]
    {
        new { Resource.Id = 1, SystemId = 17 },
        new { Resource.Id = 2, SystemId = 7 }
    }
));
0

There are 0 best solutions below