DEV Community

Discussion on: C# and .NET Core Appreciation Post. The most beautiful piece of code I have ever seen... this month!

Collapse
 
kbiel profile image
Ken in NH

I will add my voice to the others here who recommend avoiding LINQ syntax. Most MS development shops have gotten away from LINQ syntax and your query shows one good reason:

It might be more efficient for the where to execute before the join. With the LINQ syntax you can do it but it looks odd.

var user = (from t in _context.Tokens
    where t.Body == token
    join u in _context.Users
        on t.UserId equals u.Id
    select u).SingleOrDefault();

Now compare:

var user = _context
    .Tokens
    .Where(t => t.Body == token)
    .Join(
        _context.Users,
        t => t.UserId,
        u => u.Id,
        (t, u) => u)
    .SingleOrDefault();

For your specific case, I suggest you turn _context.Tokens into an IDictionary<string, Token> or even IDictionary<string, User> where the token body is the key. Then your method looks like this:

#nullable disable
private User GetUserByToken(string token)
    => _context.UsersByToken.TryGetValue(token, out var user)
    ? user
    : default;
#nullable restore
Collapse
 
sduduzog profile image
Sdu

I have a question with this one. How would my DBContext class look like, will this UsersByToken field have to be mapped to a table in the bd too?

One thing that has been mentioned a couple of times is that I should consider using IDictionary, I'm looking forward to it

Collapse
 
kbiel profile image
Ken in NH

Ah. I did not know what _context was and I was not aware you were using EF. I assumed _context was some kind of property bag or class you controlled. So, the answer is no you would not have a UsersByToken property on your DbContext and it would not map to the database. Instead it should be a local field/property in your login class. Now that I understand you are making round trips to the database, you will find IDictionary<> to be even more efficient than your current code, but you will need a fall back to retrieving the user from the database if it is not found associated the provided token in your dictionary.

Thread Thread
 
sduduzog profile image
Sdu

Thank you for this. Seems like IDictionary and IQueryable are my best bet for getting the most out of EF