0

Sorry about this - I'm new to entity framework and I'm not having much luck finding an answer anywhere else.

I have 2 tables, Users and Roles, with a many to one relationship.

Using SQL to get the users role name I'd do something like this:

SELECT r.Name 
FROM Role r
INNER JOIN User u ON u.RoleID = r.ID
WHERE u.UserName = 'someusername'

So in EF I think I should be able to do something like this:

string role = context.Users.Single(u => u.UserName == username).Role.Name;

This works fine but when the code runs it executes 2 queries on the SQL server - one to get the user from the user table and another to get the role from the roles table. This obviosuly seems very heavy compared to the SQL code above so I was wondering how I could make it more efficient and execute in a single query.

Thanks

1 Answer 1

1

Without seeing your models its a little bit tricky to tell if this is right, but you could look to do it all in 1 query like so:

string role = context.Users.Where(u => u.Username == username).Select(u => u.Role.Name).FirstOrDefault();

The code will not run any SQL until the FirstOrDefault is called.

In your scenario, by calling Single, you are executing the username check in SQL, and then the other properties are being lazy loaded in.

Sign up to request clarification or add additional context in comments.

3 Comments

why don't use string role = context.Users.FirstOrDefault(u => u.Username == username).Select(u => u.Role.Name);
Thewads answer ran in a single query. I think it was the confusion with Single that was the problem. Thanks
@Veikedo when you call FirstOrDefault it runs the SQL, and then will lazy load in the role name afterwards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.