# Cross context joins in .NET

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;
}

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

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;

• and how would you use await in this case? – Dimitri Aug 29 '16 at 10:51
• @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. – t3chb0t Aug 29 '16 at 10:54