2010-02-05 80 views
1

我有以下模式:的EntityFramework - LINQ加入帮助

客户 - 客户端Id 用户 - 用户ID 办事处 - OfficeId

ClientOffices - 客户端Id,OfficeId UserOffices - UserId,OfficeId

加粗实体是EntityFramework实体。

现在我需要编写一个接受UserId的函数并返回一个客户端列表 - 它们也属于用户所属的办公室。 Say ABC Inc.与伦敦办公室合作,XYZ Inc.与纽约办公室合作。 用户“Yakoon”仅适用于Lond Office。

在执行时应该只返回ABC公司 如果“Yakoon”属于纽约办事处为好,那么它应该返回BTOH ABC和XYZ公司的LINQ声明

感谢

回答

2

实体框架等效的方法是这样的:

public IEnumerable<Client> GetClientsForUser(int id) 
{ 
    return (from u in objectContext.Users 
      where u.UserId == id 
      from o in u.Offices 
      from c in o.Clients 
      select c); 

} 

请确保您的UserOffices和ClientOffices表上有主键,以便EF将它们识别为联结表。

+0

感谢您的大力帮助......按预期工作! – effkay 2010-02-05 13:31:05

1

这个怎么样:

public IEnumerable<Client> GetClientsForUser(int id) 
{ 
    return (from u in userOffices 
    where u.UserId == id 
    join o in clientOffices on u.OfficeId equals o.OfficeId 
    join c in clients on o.ClientId equals c.ClientId 
    select c); 
} 
+0

thx ..但o在VS中没有被识别....让我想一下这些行; – effkay 2010-02-05 09:58:01

+0

快速测试后立即更新,应该立即开始工作。 – 2010-02-05 10:07:34

+0

谢谢....为此付出的努力;是的,它应该起作用,但现在还有另一个问题; EF在userOffices中隐藏FK列,将其作为集合公开。我看到了可以做的事情。 – effkay 2010-02-05 11:24:24