0

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

    [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 集合标记为结果列还是忽略列?我只是在文档中找不到任何这样的例子。

4

1 回答 1

0

这是迄今为止我发现的最直观的方法。它适用于单个实体,但是当我想获取它们的集合时,我遇到了 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;
        }
    }
于 2014-02-11T15:02:01.070 回答