【发布时间】:2009-07-24 07:54:08
【问题描述】:
我正在使用以下查询(主要来自我收到的帮助 here):
public IEnumerable<Entities.AuditAgency> GetAuditRuleAgencyRecords(IEnumerable<Entities.AuditRuleEnterprise> rules)
{
using (LinqModelDataContext db = new LinqModelDataContext())
{
// Left-Outer Joins on Agency and its various other tables.
var auditAgencyRecords = (from ag in db.Agencies
join ara in db.AuditRuleAccounts on ag.Agency_Id equals ara.AgencyID into aran
from ara in aran.DefaultIfEmpty()
join arr in db.AuditRuleResults on ara.AuditRuleAccountID equals arr.AuditRuleAccountID into arrn
from arr in arrn.DefaultIfEmpty()
join are in db.AuditRuleEnterprises on arr.AuditRuleEnterpriseID equals are.AuditRuleEnterpriseID into aren
from are in aren.DefaultIfEmpty()
select new
{
AgencyID = ag.Agency_Id,
AgencyName = ag.Agency_Name,
AuditRuleEnterpriseID = arr.AuditRuleEnterpriseID,
AuditRuleEnterpriseName = are.OverrideDisplayName,
CorrectedDate = arr.CorrectedDate,
NbrDaysToCorrect = arr.NbrDaysToCorrect,
});
IEnumerable<AuditAgency> AuditAgencies = auditAgencyRecords
.GroupBy(a => a.AgencyID)
.Select(ag => new AuditAgency()
{
AgencyID = ag.Key,
AgencyName = ag.First().AgencyName,
Rules = ag
.GroupBy(agr => agr.AuditRuleEnterpriseID)
// ----> Do a left outer join on parameter "rules" object and the returned group above
// ----> on both of their ID's
.Select(agrg => new AuditAgencyRule() // Now I would like to only be creating "rules" for the rules with IDs that match the rules passed into this method
{
AuditRuleID = agrg.Key,
AuditRuleName = agrg.First().AuditRuleEnterpriseName,
Days = (Int32)agrg.Average(agrgr => agrgr.NbrDaysToCorrect)
})
}).ToList();
return AuditAgencies;
}
这会返回一个 AuditAgency 对象列表,每个 AuditAgency 都包含一个 AuditAgencyRules 列表。
现在,作为此查询的最后一步,我遇到问题的部分是,您可以看到一个 IEnumerable 规则作为参数传入此方法。
我想做的是在我的第二个查询中,它为每个机构创建一个规则列表,我想对我的本地“规则”对象进行左外连接。我传入的每个规则对象都有一个 rule.ID。我希望每个机构只包含传入的规则,如果没有数据,则只需将其内容留空即可。
现在,我的查询包含从数据库返回的所有规则及其数据。但是,我需要它只包含传递给方法的规则,无论它是否与从数据库返回的规则匹配。所以换句话说,我需要在我的本地“规则”对象上使用我现在拥有的规则进行左外连接。
你可以看到我在上面的代码中添加了 cmets 来解释我在哪里以及我想要做什么。
因此,如果“规则”仅包含 3 个设置了 ID 的规则,那么此查询将只返回每个代理机构的这 3 个规则,而不管这些规则是否有数据(其数据将为空)。而不是返回每个机构的所有规则,这就是它现在所做的。
如何在我的 LINQ to SQL 查询中为“本地”对象编写这个左外连接?
这是我在上面的第二个查询之后尝试对我的“规则”对象和我的 AuditAgencies 中的规则进行左外连接:
foreach (var agency in AuditAgencies)
{
agency.Rules = from rule in rules
join lr in agency.Rules on rule.EnterpriseID equals lr.AuditRuleID into g
from lr in g.DefaultIfEmpty()
select new AuditAgencyRule
{
AuditRuleID = rule.EnterpriseID,
AuditRuleName = rule.Name,
Days = lr.Days,
Flagged = lr.Flagged,
PercentFlagged = lr.PercentFlagged
};
}
没有骰子。现在,我得到的不是所有规则,而是 ~no~ 规则。当我只想获取我传递给此方法的规则时。
有人能指出正确的方向吗?
【问题讨论】:
标签: c# linq linq-to-sql linq-to-objects