Populating entity properties after seeding entities in EF Core

23 views Asked by At

I have the following class, where NextNode points to another instance of the Node class:

public class Node
{
    public int Id { get; set; }
    public int? NextNodeId { get; set; }
    public Node? NextNode { get; set; }
    ...
}

Since I can't reference a node that doesn't yet exist in the NextNode property, is it possible to seed the database in two steps?

First create, the nodes, and then second, populate the NextNode property?

1

There are 1 answers

0
Guru Stron On

Since you will generate the Ids you can simply fill in the NextNodeId's without filling NextNode for HasData:

modelBuilder.Entity<Node>()
    .HasData(new List<Node>
    {
        new Node
        {
            Id = 1,
            NextNodeId = 2
        },
        new Node
        {
            Id = 2
        }
    });

If you decide to create custom seeding code with Add(Range) + SaveChanges(Async) then you can just create corresponding hierarchy and add it, EF should be able to handle this:

ctx.Nodes.AddRange(new Node
{
    Id = 1, // skip ids if they are database generated
    NextNode = new Node
    {
        Id = 2 // skip ids if they are database generated
    }
});
ctx.SaveChanges();