Insert entity with navigational properties

28 Views Asked by At

I have an entity business owner given below. It is recursive entity with ParentBusinessOwner property.

public class BusinessOwner : ISystemOperated, ICachable
{
    [Key]
    public int BusinessOwnerId { get; set; }

    [StringLength(200)]
    public string? Logo { get; set; }

    public virtual BusinessOwner? ParentBusinessOwner { get; set; }

    [StringLength(50, MinimumLength = 3)]
    public string DisplayName { get; set; }
}

To insert an entity with a parent entity i am loading the parent entity from dbSet first and then assigning it to new entity. I think its an expensive approach as my other entities have several referential entities.

         if (model.ParentBusinessOwnerId.HasValue)
            {
                var parent = await _appDbContext
                     .BusinessOwners
                     .SingleAsync(p => p.BusinessOwnerId == model.ParentBusinessOwnerId);

                entity.ParentBusinessOwner = parent;
            }

What is the best way of adding relationships to existing data in database?

0

There are 0 best solutions below