从一个表连接一行,从另一个表连接两行

时间:2016-01-19 15:57:28

标签: c# sql linq linq-to-sql

我有两个包含以下架构的表:

Location table:
Location_PK, Person_K, Status_K, Reason_K, Name etc some other columns

and Reference table:
Reference_PK, Description.

例如,位置表中的行可能如下所示: L123,P4,R123,R456,“货运大楼”

然后 R123和R456 是可以在参考表中找到主键的值

R123, "Roof repair"
R456, "Hail Damage"

现在我想编写一个显示Location表中信息的查询,而不是R123,R456可以显示Reference表中的实际描述。这是我编写联接but it does not return any records.的伪版本 同样我希望它输出为字典,密钥为 Person_K ,以便稍后我可以访问每个人的信息。

 public Dictionary<string, PersonLocationInfo> GetAllInfo(List<string> allProviderKeys)
    {
        var query = (from ea in this.Context.Locations
            join r1 in this.Context.Reference on ea.Reason_K equals r1.Reference_PK
            join r2 in this.Context.Reference on ea.Status_K equals r2.Reference_PK
            where (allProviderKeys.Contains(ea.Provider_K)
                )
            select new PersonLocationInfo
            {
                PersonKey = ea.Person_K,
                Reason = r1.Description.Trim(),
                Status = r2.Description.Trim()
            }
            ).ToDictionary(x => x.ProviderKey);

        return query;
    }

public class PersonLocationInfo
{
    public string Reason { get; set; }
    public string Status { get; set; }
    public string PersonKey { get; set; }
}

0 个答案:

没有答案