.NET CQRS 的实现中引入 ReadOnlyRepository

采用 CQRS 架构实现 Query 与 Command 的分离,带来的一个好处是可以将 Query 所使用的 DbContext 设置为 QueryTrackingBehavior.NoTracking,彻底关闭 EF Core 在查询时的实体跟踪功能。

昨天本来准备专门针对 Query 实现 ReadOnlyDbContext,后来在这篇博文 EF Core Change Tracking: The Bug Factory You Accidentally Built 中发现了一个更好的解决方法 —— 引入 ReadOnlyRepository,在 ReadOnlyRepository 中关闭 DbContext 的实体跟踪。

于是按照这个解决思路实现了 IReadOnlyRepository<TEntity>ReadOnlyRepository<TEntity>,代码如下:

IReadOnlyRepository.cs

public interface IReadOnlyRepository<TEntity>
    where TEntity : class
{
    IQueryable<TEntity> GetAll();
}

ReadOnlyRepository.cs

public class ReadOnlyRepository<TEntity> : IReadOnlyRepository<TEntity>
    where TEntity : class
{
    private readonly CnblogsDbContext _dbContext;

    public ReadOnlyRepository(CnblogsDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }

    public IQueryable<TEntity> GetAll()
    {
        return _dbContext.Set<TEntity>();
    }
}
posted @ 2026-02-23 11:39  dudu  阅读(17)  评论(0)    收藏  举报