0

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?

5
  • Use _appDbContext.BusinessOwners.Find(model.ParentBusinessOwnerId). From question also not clear what is expensive. How many objects do you insert? Commented Dec 27, 2023 at 14:36
  • expensive in the sense i only have to save business owner which has 6 related entities, do i need to find all and assign to my businessOwner object to add the relationship to this object? Commented Dec 27, 2023 at 18:17
  • .Find() also assigns the object from context if already tracked, otherwise will bring the object from db and attaches to context as well as assigns to the property. My question is , in entity framework if we always have to assign a complete object to the dependent properties? Commented Dec 27, 2023 at 18:30
  • for example my businessOwner has 5 other properties, for other properties i should find from their dbsets and assign to my object in the same way? for example in sql inserts what we do we only create an insert statement with ids for its related tables and one statement is enough, but here whenever we run find on different dbsets they are retrieved from db. Commented Dec 27, 2023 at 18:31
  • Assign Ids then, EF should be happy with that. Otherwise, yes whole objects should be loaded or proper fakes attached. Commented Dec 27, 2023 at 20:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.