mardi 2 octobre 2018

Using DbContext instance inside the entity class

Recently I've started learning Entity Framework Core and I'm curious if it's fine to use DbContext instance inside the entity class.

Sample code:

class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Order> Orders { get; set; }

    public void LoadOrders() {
        using (var context = new StoreContext()) {
            Orders = context.Orders             
                .Where(x => x.UserId == Id)
                .ToList();
        }
    }
}

User entity has a relation with Order class, both of them have appropriate tables in the DataBase created using migrations from Entity Framework. The purpose of LoadOrders() method is simply to load related entities for current user when it's necessary.

Now I wanted to know if that's a valid approach?

Or maybe I should always load related entities at the same time when I'm loading the parent object? (E.g. .Include().ThenInclude())

Or maybe the code of LoadOrders() method should be located in some additional class like UserHelper that would be used along with the User entity.

Aucun commentaire:

Enregistrer un commentaire