LINQ到Entities:在查询中组合两个不相关的表
我有两张桌子:LINQ到Entities:在查询中组合两个不相关的表,linq,entity-framework,Linq,Entity Framework,我有两张桌子: Relationships (ID, UserID, Type, Contact ID) Contacts (ID, Name, Address) 当关系表中的类型为5时,联系人ID是联系人表中的ID 我想获取特定用户的所有联系人信息 以下是我所拥有的: IEnumerable<Relationship> rels = user.Relationships.Where(r => r.Type==5) foreach (Relati
Relationships (ID, UserID, Type, Contact ID)
Contacts (ID, Name, Address)
当关系表中的类型为5时,联系人ID是联系人表中的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);
}
IEnumerable rels=user.relations.Where(r=>r.Type==5)
foreach(rels中的关系r)
{
contact=contactRepository.Find(r.ContactID);//返回联系人对象
关系=新关系(r,联系人);
关系列表。添加(关系);
}
这样做正确吗
我看过其他提到TPC的帖子。然而,我并不完全理解这一点,TPC似乎只适用于代码优先的流程。您可以使用linq语句,通过使用Relationships和contacts表获得给定用户ID(假设用户ID=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;
通过使用Relationships和contacts表,您可以使用user 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;
有一个类似的问题使用Select()和Union()给出答案。请检查:有一个类似的问题使用Select()和Union()给出答案。请检查: