views:

22

answers:

1

Hi guys, This is my first question in stackoverflow but really not the first time to get solution here. I am struggling with multiple join in entity framework 4. I have three tables (Accounts, Users and AccountUsers) that am finding difficult to query.

What I want is to get all the users for the provided accountId including the account creator. I can get all the account users with no problem but the hard side for me is getting the account creator since it's not added to AccountUsers table. below is a quick preview how the tables are related.

Accounts

  • AccountId
  • UserId (account creator)
  • ...other columns

Users

  • UserId
  • ...other columns

AccountUsers

  • AccountId
  • UserId

I would prefer the query to be esql, but Linq to Entities will do.

I trust you guys on stackoverflow, so I know this won't take long to get the 'Answer' mark.

Thanks for even reading.

A: 

If I'm reading your question right, you're not looking for a join so much as a union? I'm not sure about esql, but I'd think the following Linq query should work. Maybe it will get you going in the right direction (or I could be completely off-base or missing something):

var users = (from accountUser in db.AccountUsers
             where accountUser.AccountId == myAccountId
             select accountUser.UserId)
            .ToList()
            .Add((from account in db.Accounts
                  where account.AccountId == myAccountId
                  select account.UserId)
                 .Single());

To make it lazy loading, you could always make a method that makes use of foreach and yield return:

IEnumerable<int> GetAccountUsers(int AccountId)
{
    //return the users
    foreach(var userId in (from accountUser in db.AccountUsers
                           where accountUser.AccountId == myAccountId
                           select accountUser.UserId))
        yield return userId;

    //return the owner too
    yield return (from account in db.Accounts
                  where account.AccountId == myAccountId
                  select account.UserId)
                 .Single();
}

Out of curiosity, though, why is the owner not also added to the AccountUsers table?

lc
Maybe what i need is union, am not sure. Your query seems to execute twice, the .ToList() and .Single(). I want the query to execute once, if union will do then i'll go for it, am not just that good at the query stuff. The owner is not added to the AccountUsers table since the account table already has the UserId that indicates the AccountOwner.
Syma