jmorc
jmorc

Reputation: 570

Applying a self-referential ID in EF Core for newly created entities

I've inherited a project with an Entity parent/child hierarchy. Despite the ParentId being nullable, it was designed such that an entity with no parent has its ParentId set to its own Id. There are lots of workflows that rely on this convention, so it must continue to be followed.

Is there anything in EF I can do to set the ParentId equal to the Entity's Id when creating new Entities in one database trip? For now I'm just saving it with no ParentId, getting the newly generated Id, assigning it to ParentId as well, and saving again.

public partial class Entity
{
    public long Id { get; set; }
    public long? ParentId { get; set; }
}

Upvotes: 1

Views: 106

Answers (1)

Neil
Neil

Reputation: 11889

It should be automatically handled by EF if you do this:

public partial class Entity
{
    public long Id { get; set; }
    public long? ParentId { get; set; }
    public Entity Parent { get; set; }
}

var entity = new Entity();
entity.Parent = entity;
SaveChanges();

Upvotes: 1

Related Questions