2
\$\begingroup\$

This is how I made a cross context join.

What do you think?

How would you do this better?

using (var context = ContextFactory.Create())
{
    var users =  await context
                         .Users.AsNoTracking()
                         .OrderBy(user => user.DisplayName)
                         .Where(user => user.AccountName.Contains(query))
                         .Select(user => new UserProfileDTO
                         {
                             Id = user.Id,
                             DisplayName = user.DisplayName,
                         })
                         .ToListAsync().ConfigureAwait(false);

    foreach (var user in users)
    {
        var entity = await context.UserInfos.FindAsync(user.Id).ConfigureAwait(false);
        if (entity != null)
            user.HasPicture = entity.HasPicture == true ? true : false;
    }

    return users;
}
\$\endgroup\$
  • \$\begingroup\$ What do you mean by cross-context? I can see only one context there. \$\endgroup\$ – t3chb0t Aug 29 '16 at 8:19
  • \$\begingroup\$ @t3chb0t context.Users and context.UserInfos ? \$\endgroup\$ – Dimitri Aug 29 '16 at 8:19
  • \$\begingroup\$ Aren't those tables? \$\endgroup\$ – t3chb0t Aug 29 '16 at 8:20
  • \$\begingroup\$ oh, yes. So it isn't cross context ? \$\endgroup\$ – Dimitri Aug 29 '16 at 8:23
  • \$\begingroup\$ cross context would be between two databases - this is just a normal join between two tables \$\endgroup\$ – t3chb0t Aug 29 '16 at 8:24
2
\$\begingroup\$

You can get the results with a single query like this one:

var result = await
    (from u in context.Users
     join ui in context.UserInfos on u.Id equals ui.UserId
     where u.AccountName.Contains(query) && ui.HasPicture
     select new UserProfileDTO
     {
         Id = u.Id,
         DisplayName = u.DisplayName,
     }
    ).ToListAsync().ConfigureAwait(false);

This would select all users with a picture in their user-info.

I assumed the UserInfo table has a foreign-key UserId that you can use for joining both tables.


This by the way

user.HasPicture = entity.HasPicture == true ? true : false;

is the same as:

user.HasPicture = entity.HasPicture;
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ and how would you use await in this case? \$\endgroup\$ – Dimitri Aug 29 '16 at 10:51
  • \$\begingroup\$ @SGN same as you did. you wrap it with () and add the .ToListAsync().ConfigureAwait(false) at the end and async in front of the query - I added it to the answer. \$\endgroup\$ – t3chb0t Aug 29 '16 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.