mercredi 17 mars 2021

Entity Framework Core - Better to add child data through parent?

Say I have something like this...

public class Parent
{
    public Guid Id { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public Guid Id { get; set; }
    public Guid ParentId { get; set; }
    public Parent Parent { get; set; }
}

...and I want to add child data to the database. All of the examples I've seen are of the child data being added through the parent's collection (e.g. parent.Children.Add(child) -> SaveChanges()). But if the data is coming through a Web Api where the child's ParentId is already set to the appropriate parent, then I'm wondering if I should just add the child directly to the context instead of making the extra roundtrip to retrieve the parent. I should add, that at least in this case, a Child cannot exist without its Parent.

I guess an advantage is that it gives a way to check for the existence of the parent first, but I'll likely have some form of DbException catching anyway for other scenarios. Another advantage might be the ability to enforce domain logic if the Parent class has an AddChild method, but this logic could also be captured in other ways. Are there any other advantages? Is it worth the extra roundtrip?

I'm leaning towards adding it through the parent because it feels a bit clearer/cleaner -- especially if the Child requires a Parent -- but I'm in the process of porting a lot of legacy api code (which used to add child data directly to the context) from a different ORM and I'm worried I'll end up regretting my decision and have to change it all.

Thanks.

Aucun commentaire:

Enregistrer un commentaire