假设我的域名中有以下对象。
[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集合标记为结果还是忽略列?我只是在文档中找不到这样的例子。
答案 0 :(得分: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;
}
}