LINQ TO实体:在查询中组合两个不相关的表

时间:2013-01-05 05:35:03

标签: linq entity-framework

我有两张桌子:

Relationships (ID,   UserID,   Type,   Contact ID)   

Contacts (ID,   Name,  Address) 

当关系表中的类型为5时,Contact ID是Contacts表中的ID。

我想获取特定用户的所有联系信息

这就是我所拥有的:

IEnumerable<Relationship> rels  = user.Relationships.Where(r => r.Type==5)
foreach (Relationship r in rels)
{
            contact = contactRepository.Find(r.ContactID);  // Returns Contact Object 
            Relation relation = new Relation(r, contact);   
            RelationList.Add(relation);

 }

这是正确的方法吗?

我见过其他提到TPC的帖子。但是,我并不十分了解所有这些,而且似乎TPC仅适用于代码优先处理。

1 个答案:

答案 0 :(得分:0)

您可以通过使用关键字和联系人表来使用followng linq语句来获取给定用户ID的联系人(假设UserID = 15):

var contacts=from r in Relationships
             join c in Contacts on r.ContactID equals c.ID
             where r.Type=5 and r.UserID=15
             select c;
相关问题