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

DDD中:多表聚合查询结果对象属于实体、值对象还是其他?

DDD中聚合查询结果对象的类型判定

核心概念区分

  • 实体:以唯一身份标识(ID)定义相等性,即使属性发生变化,只要身份标识不变,就视为同一个对象。
  • 值对象:以所有属性的组合值定义相等性,对象不可变,无独立身份标识。

CustomerInteraction的定位

CustomerInteraction对象符合实体的核心特征:它以CustomerId作为身份标识来判断相等,而非依赖购买次数等属性值——即使NumberOfPurchasesInThePastMonth的数值变化,只要CustomerId相同,就代表同一个客户的交互数据。

虽然它没有对应独立的数据库表,是多表关联查询的计算结果,但这并不影响它的实体属性。它属于只读的领域视图实体,本质上是实体范畴下的一种特殊形式,核心还是依赖身份标识来确定唯一性。

代码实现建议

为了明确其实体特性,建议重写相等判断方法,基于CustomerId实现:

public class CustomerInteraction
{
    public int CustomerId { get; private set; }
    public int NumberOfPurchasesInThePastMonth { get; private set; }

    public CustomerInteraction(int customerId, int numberOfPurchases)
    {
        CustomerId = customerId;
        NumberOfPurchasesInThePastMonth = numberOfPurchases;
    }

    public override bool Equals(object obj)
    {
        if (obj is not CustomerInteraction other)
            return false;
        return CustomerId == other.CustomerId;
    }

    public override int GetHashCode()
    {
        return CustomerId.GetHashCode();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:00:00