2010-11-30 9 views
1

私はUserテーブルとContactIdカラムのみを含むContactテーブルを持っているので、この古典的なシナリオがあります。私が望むのは、指定されたUserとの共通の連絡先の番号を持つuserIdのリストを私に提供するクエリです。昔ながらのSQLで、私は(ユーザーおよびユーザー自身の連絡先は、友人の提案のようにFacebookを利用して取得するために除外された)次のクエリを持っている:エンティティフレームワークの共通の連絡先(自己多対多の関係)

SELECT COUNT(c1.ContactId) as CommonContact, c2.UserId 
from Contacts as c1 
inner join Contacts as c2 on c1.ContactId = c2.ContactId 
Where c1.UserId = @Id AND c2.UserId != @Id 
AND c2.UserId NOT IN (SELECT ContactId from Contacts Where UserId = @Id) 
Group By c2.UserId 
ORDER BY CommonContact Desc 

この単純なクエリは素晴らしい作品が、私は同じことを書く方法を見つけ出すことはできませんエンティティへのLINQでのクエリ、Entity Frameworkのモデルでは、私は、エンティティが連絡先のナビゲーションプロパティを持っていますが、接続テーブルが直接存在しないユーザエンティティを持っているので....任意の助け

おかげでたくさん...

+0

は、私は1つの関係に多くの、多くの一つに、多くの多くを行いますあなたの接続テーブルにいくつかのIDフィールドを追加することをお勧めします、あなたはうまくそれらを照会することができるようになります。実際には、接続に加えて常にいくつかの特別な属性があるため、本当に多対多の関係はありません。リレーションが作成または更新されたとき、そのステータス、アクティブ、ブロックされたときなど –

答えて

0

時間が無く、実行しようとしましたが、このようなものはうまくいくはずです。

public class Test 
    { 
     //simulate an IQueryable 
     private readonly IQueryable<Person> _people = new List<Person>().AsQueryable(); 

     public void FindContactMatchCount(Guid personId) 
     { 
      //we'll need the list of id's of the users contacts for comparison, we don't need to resolve this yet though so 
      //we'll leave it as an IQueryable and not turn it into a collection 
      IQueryable<Guid> idsOfContacts = _people.Where(x => x.Id == personId).SelectMany(x => x.Contacts.Select(v => v.Id)); 

      //find all the people who have a contact id that matches the selected users list of contact id's 
      //then project the results, this anonymous projection has two properties, the person and the contact count 
      var usersWithMatches = _people 
       .Where(x => idsOfContacts.Contains(x.Id)) 
       .Select(z => new 
        { 
         Person = z, //this is the person record from the database, we'll need to extract display information 
         SharedContactCount = z.Contacts.Count(v => idsOfContacts.Contains(v.Id)) // 
        }).OrderBy(z => z.SharedContactCount) 
       .ToList(); 
     } 
    } 
関連する問題