Search code examples
entity-framework-coreinsert.net-6.0table-per-type

How to modify inserting order in ef core 6 with Table-Per-Type Hierarchy


Is there a way to define a different order of inserting elements when Table-Per-Type is used? I have this structure:

public class Register { 
    [Key] public int Id { get; set; } 
    public string Name { get; set; } 
}
public class RegisterPartiality : Register { ... }
public class RegisterDelayed : Register { 
    public Register Parent { get; set; } 
}

When I tried to add 3 registers they are inserted by table name order.

var reg1 = new Register{ Name = "1" };
var reg2 = new RegisterPartiality{ Name = "2" };
var reg3 = new RegisterDelayed{ Name = "3", Parent = reg2 };

Resulting in:

Id Name Parent (Only for RegisterDelayed)
1 1 -
2 3 3
3 2 -

So strange that parent of an element it's a higher number.

If I change the name of 2nd table then it's working as expected, so I ask if there's a way to tell EF with TPT which table save first?

public class Register { 
    [Key] public int Id { get; set; } 
    public string Name { get; set; } 
}
public class RegisterBias : Register { ... }
public class RegisterDelayed : Register { 
    public Register Parent { get; set; } 
}
Id Name Parent (Only for RegisterDelayed)
1 1 -
2 2 -
3 3 2

Solution

  • As said here.

    "There isn't any way to change this when using generated IDs. The actual values used for IDs should not be important. If it is, then it would be better to specifically assign them."