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?
_appDbContext.BusinessOwners.Find(model.ParentBusinessOwnerId). From question also not clear what is expensive. How many objects do you insert?