2010-11-30 3 views
1

UserAld 및 ContactId 열만 포함하는 연락처 테이블이있는이 고전적인 시나리오가 있습니다. 내가 뭘하고 싶은 건지 나에게 지정된 사용자와 일반적인 연락처의 번호와 userIds의 목록을 제공하는 쿼리입니다.엔티티 프레임 워크에서 공통 연락처 쿼리 (자 대다 관계가 많음)

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 

이 간단한 쿼리가 잘 작동하지만 같은를 작성하는 방법을 알아낼 수 없습니다 : 보통 오래된 SQL에서 나는 쿼리 다음 (사용자와 사용자의 접촉 자체가 친구의 제안처럼 페이스 북을 얻기 위해 필터링한다)이 엔티티에 LINQ 쿼리, 엔티티 프레임 워크 모델에서 나는 엔티티가 연락 탐색 속성이 사용자 개체가 있기 때문에 연결 테이블이 직접이 없다 ....

감사합니다 어떤 도움을 많이 ...

+0

나는 하나 개의 관계에 많은 많은 하나에 많은 많은 것 연결 테이블에 일부 신원 필드를 추가 제안합니다 당신은 친절을 조회 할 수 있습니다. 실제로 우리가 항상 연결과 함께 몇 가지 추가 특성을 가지고 있기 때문에 실제로는 많은 관계가 존재하지 않습니다. 관계가 생성되거나 업데이트 될 때, 활성 상태, 차단 된 상태 등과 같이 –

답변

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(); 
     } 
    } 
관련 문제