我使用 DDD 方法使用 Entity Framework 有一段时间了,但现在我对查询的性能有一些疑问:每次我从 AggregateRoot 存储库加载和聚合时,我加载整个 AggregateRoot 与所有列和包含而不是加载只加载我需要的列。当然,这很慢。
让我用一个例子来解释:
public class User : AggregateRoot {
public Guid Id { get; private set; }
public string Name { get; private set; }
public string Surname { get; private set; }
public int Followers { get; private set; }
public List<SomeOtherEntity> SomeOtherEntities { get; private set; }
//...
public void IncreaseFollowers()
{
Followers++;
}
}
//Repository
public class UserRepository : IUserRepository {
//...injections
public User GetById(Guid id) {
return _database
.Users
.Include(x => x.SomeOtherEntities)
.FirstOrDefault();
}
}
所以,在我的处理程序中(我使用的是 CQRS 模式),每次我需要获取一个用户实体时,我都必须加载整个实体的所有包含,没有任何优化,例如
.AsNoTracking()
或其他。
例如,如果我需要增加用户的关注者,我应该这样做:
public class IncreareUserFollowerCommandHandler : IHandler<.,.> {
//..injections
public void Handle()
{
var user = _userRepo.GetById(request.Id);
user.IncreaseFollowers();
_userRepo.Update(user);
_userRepo.SaveChanges();
}
}
那么问题来了:DDD和EF如何共存?可能问题是 AggregateRoot 的存储库的通用性质? 在这个例子中,我只需要增加一个数字,所以,如果我不使用存储库或 DDD 方法,我可以只加载我需要的列仅更新该列,而无需每次都加载整个聚合!
非常感谢您的任何建议! :)