You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core继承场景下,业务逻辑层该如何设计?

EF Core继承场景下的业务逻辑层设计方案探讨

EF Core中的继承(TPH、TPT、TPC)是处理属性高度相似实体的实用特性,但我常和同事在业务逻辑层的设计上产生分歧。

实体定义

public class FruitEntity {}

public class AppleEntity : FruitEntity {}

public class PearEntity : FruitEntity {}

我们采用**仓储模式(Repository Pattern)**实现数据访问层,当前核心疑问是:业务逻辑层该如何设计?

现有两种设计方案

方案1:为每个实体单独创建Service

我倾向于给每个实体单独实现Service,这种设计职责清晰分离,修改任一Service时不会影响其他实体的用例,符合单一职责原则。

AppleService实现:

public class AppleService 
{
    private readonly IRepository<AppleEntity> _appleRepository;

    public AppleService(IRepository appleRepository) {
         _appleRepository = appleRepository ?? throw new ArgumentNullException();
    }

    public async Task<AppleEntity> GetAsync(Guid appleId)
    {
        // 更多业务逻辑
        
        return await _appleRepository.GetAsync(appleId);
    }
}

PearService实现:

public class PearService 
{
    private readonly IRepository<PearEntity> _pearRepository;

    public PearService(IRepository pearRepository) {
         _pearRepository = pearRepository ?? throw new ArgumentNullException();
    }

    public async Task<PearEntity> GetAsync(Guid pearId)
    {
        // 更多业务逻辑
        
        return await _pearRepository.GetAsync(pearId);
    }
}

但同事指出这种方案存在测试冗余问题:几乎相同的方法都需要单独编写测试用例。

方案2:基于抽象基类的Service设计

为了减少测试开销,同事提出用抽象基类的设计方案,大部分代码可通过委托实现,测试开销能大幅降低,最优情况下可减半。

代码示例:

public abstract class FruitService{}

public class AppleService : FruitService{}

public class PearService : FruitService{}

问题

除了上述两种方案,还有其他可采用的设计风格、模式吗?


内容的提问来源于stack exchange,提问作者liqSTAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:05:58