0

I've been thinking this for a while. Is there an easy way to use the result querying a database twice without storing the result of the query in some variable? Say I have a

string ResearchAdmin;

where I want to put the 'FirstName' and 'Surname' found in 2 different columns in a 'ProjectResearcher' table in the database. Can I query the database just once (using say entity framework), and get both columns without storing the entire table's data.

To illustrate my point, doing the code below will I think query the database twice, once to get the 'FirstName', once to get the 'Surname':

ResearchAdmin = db.ProjectResearcher.FirstOrDefault(r => r.ProjectId == project.ProjectId).Researcher.FirstName + " " + db.ProjectResearcher.FirstOrDefault(r => r.ProjectId == project.ProjectId).Researcher.Surname

To run the query once I can do the following:

Researcher researchAdmin = db.ProjectResearcher.FirstOrDefault(r => r.ProjectId == project.ProjectId).Researcher;
String researchAdminName = researchAdmin.FirstName + " " + researchAdmin.Surname;

What I'm wondering is if I can do the first option somehow without querying the database twice.

2 Answers 2

2

You could do something like this:

String researchAdminName = db.ProjectResearcher.Where(r => r.ProjectId == project.ProjectId)
        .Select(r => r.FirstName + " " + r.Surname).FirstOrDefault();

Just have to be a little careful that whatever you are putting into the select statement is supported by linq to entities, but simple string concatenation is.

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

Comments

1

Thewads answer looks correct and it will give you what you need.

An alternative: Wrap logic in Stored Proc (certainly an overkill here) but for more complex manipulation its prob. better as SQL server will have a cached plan and will be faster.

Comments

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.