【问题标题】:Aggregate roots and perfomance with Entity Framework使用 Entity Framework 聚合根和性能
【发布时间】:2021-03-15 19:18:40
【问题描述】:

我正在尝试在我的项目中实现 DDD,但我遇到了性能问题,模型很简单:日历(聚合根)和约会

public class Calendar
{
    public int Id { get; private set; }

    public IList<Appointment> Appointments { get; private set; }

    public void AddAppointment(Appointment appointment)
    {
        var anyOverlapping = Appointments.Any(a => a.Date.Hour == a.Date.Hour);

        if (anyOverlapping)
        {
            throw new Exception();
        }

        // More validations according to the calendar

        Appointments.Add(appointment);
    }
}

public class Appointment
{
    public int Id { get; private set; }
    public DateTime Date { get; private set; }
    public int CalendarId { get; private set; }
}

问题在于,使用 DDD 方法时,我必须在 manager/service 方法中加载整个约会集合。

public void AddAppointment(int calendarId, Appointment appointment)
{
    var calendar = _context.Calendars
        .Include(c => c.Appointments) // Here load all the records in memory, can be thousands
        .FirstOrDefault(c => c.Id == calendarId);

    calendar.AddAppointment(appointment);
    _context.SaveChanges();
}

但是对于 no DDD 方法,管理器/服务方法是:

public void AddAppointment(int calendarId, Appointment appointment)
{
    var anyOverlaping = _context.Appointments
    .Where(a => a.CalendarId == calendarId)
    .Any(a => a.Date.Hour == appointment.Date.Hour); // Don't load all the records into memory
    
    if (anyOverlapping)
    {
        throw new Exception();
    }
    
    // More validations according to the calendar that belongs
    
    _context.Appointments.Add(appointment)
    _context.SaveChanges();
}

我怎样才能在继续使用 DDD 设计的同时继续发挥作用?

【问题讨论】:

    标签: c# performance entity-framework aggregate domain-driven-design


    【解决方案1】:

    如果这是关于仅查询用例的读取性能,您应该完全绕过域模型类并以最适合您的方式读取数据。例如。通过使用已经只获取所需数据的单独读取模型类。

    如果这是关于写入性能,我建议您使用lazy loading with the proxy package。使用该聚合的子数据将仅按需从数据库加载。唯一的事情是您需要在模型中使相应的字段虚拟化,但除了域模型之外,仍然没有任何依赖关系。我认为这是一个可以接受的权衡。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多