【问题标题】:How do I format a query to fetch an aggregate root with just related ids如何格式化查询以获取仅具有相关 ID 的聚合根
【发布时间】:2014-02-10 21:57:30
【问题描述】:

假设我的域中有以下对象。

    [TableName("work_space")]
    public class WorkSpace
    {
        public long Id { get; set; }

        [Column(Name="owner_id")]
        public long OwnerId { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public IEnumerable<int> OrgIds { get; set; }

        public IEnumerable<int> SettingIds { get; set; }

        public IEnumerable<int> UserIds { get; set; }

        public IEnumerable<long> WorkViewIds { get; set; }
    }

这是获取我需要的数据的一种方法。

SELECT ws.*, wsu.user_id as UserId, wss.setting_id as SettingId, wso.org_id as OrgId, wv.id as WorkViewId
FROM work_space ws
LEFT OUTER JOIN work_space_user wsu ON ws.id = wsu.work_space_id
LEFT OUTER JOIN work_space_setting wss ON ws.id = wss.work_space_id
LEFT OUTER JOIN work_space_org wso ON ws.id = wso.work_space_id
LEFT OUTER JOIN work_view wv ON ws.id = wv.work_space_id
WHERE ws.id = @0

这通常在 NPoco 中是如何完成的?我会使用多结果集获取吗?某种获取一对多?我将我的 ID 集合标记为结果列还是忽略列?我只是在文档中找不到任何这样的例子。

【问题讨论】:

    标签: npoco


    【解决方案1】:

    这是迄今为止我发现的最直观的方法。它适用于单个实体,但是当我想获取它们的集合时,我遇到了 n+1 个问题,因为要为集合中的每个对象返回数据库以获取关系。

        public WorkSpace GetWorkSpace(int id)
        {
            using (Database db = DbFactory.VSurveyDbFactory.GetDatabase())
            {
                WorkSpace workspace = db.SingleById<WorkSpace>(id);
    
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.Append(@"SELECT * FROM work_space_user WHERE work_space_id = @0;");
                sqlBuilder.Append(@"SELECT * FROM work_space_setting WHERE work_space_id = @0;");
                sqlBuilder.Append(@"SELECT * FROM work_space_org WHERE work_space_id = @0;");
                sqlBuilder.Append(@"SELECT * FROM work_view WHERE work_space_id = @0;");
    
                Tuple<List<int>, List<int>, List<int>, List<long>> results = db.FetchMultiple<int, int, int, long>(sqlBuilder.ToString(), id);
    
                workspace.UserIds = results.Item1;
                workspace.SettingIds = results.Item2;
                workspace.OrgIds = results.Item3;
                workspace.WorkViewIds = results.Item4;
    
                return workspace;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多