D
D
Dmitry Demin2020-06-05 21:29:58
C++ / C#
Dmitry Demin, 2020-06-05 21:29:58

Is it possible to use a child class to implement Separation of concerns when using Entity Framework?

Purpose: to inject inside the DBContext entity class for data access.
Obstacle: project architecture.

Let's say there is a MyApp.Domain project that describes domain entities.

namespace MyApp.Domain
{
    public class PlanPage
    {
        public Guid Id { get; set; }
    }
}

namespace MyApp.Domain
{
    public class PlanPageDay
    {
        public Guid Id { get; set; }
        public Guid PlanPageId { get; set; }
    }
}


Also, there is a project MyApp.Infrastructure.EntityFramework , which describes the mapping of domain entities in the database. It also has the following class.
namespace MyApp.Infrastructure.EntityFramework.Models
{
    public class PlanPageEntity : PlanPage
    {
        private readonly ApplicationDbContext _applicationDbContext;

        protected PlanPageEntity(ApplicationDbContext applicationDbContext)
        {
            _applicationDbContext = applicationDbContext;
        }
        
        public ICollection<PlanPageDay>? Days { get; set; }

        public async Task<ICollection<PlanPageDay>> GetDays()
        {
            return Days ??= await _applicationDbContext.PlanPageDays
                .Where(pd => pd.PlanPageId == Id)
                .ToListAsync();
        }
    }
}


The purpose of the example is to move the implementation of loading related entities into non-blocking methods and keep the separation of concerns that we cover in the project.
Question: Is it possible to configure the Entity framework so that the code below will work correctly?

// Код создания сущности-агрегата где-то в доменной логике
var plan = new PlanPage(/*аргументы конструктора*/);

// Код запроса сущности из БД.
public async Task<PlanPage> GetPlanPage(Guid id)
{
    return await _applicationDbContext.Set<PlanPageEntity>().FindAsync(id);
}


Note that the Entity Framework is being asked for a child extension class into which, by design, a DBContext will be provided and which implements all the guts of accessing related data.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question