Duckslayer
Duckslayer

Reputation: 119

Where clause in method syntax fails when combining strings

I am trying to retrieve a record from a database using Entity Framework and LINQ. It works mostly as expected, but for a bug with a WHERE statement I can't quite figure out.

var nodeId = "001";

//This works and returns the record I am looking for
var nodeDisplayName = ("#" + nodeId);
var filteredNodes = dbContext.Node.Where(n => n.DisplayName == nodeDisplayName).ToList();

//This does not work and returns 0 results
var filteredNodes2 = dbContext.Node.Where(n => n.DisplayName == ("#" + nodeId )).ToList();

I would expect the two variants to behave exactly the same, and they appear to do so if I run them on a List in memory. But when running against entity framework/a database they behave differently. I can fix the bug easily enough by just using the first method, but I would like to understand what causes the difference in behavior.

EDIT

So the generated SQL queries look like this:

SELECT `n`.`id`, `n`.`display_name`, `n`.`reg_tms`
FROM `tablename`.`node` AS `n`
WHERE `n`.`display_name` = '#001'

SELECT `n`.`id`, `n`.`display_name`, `n`.`reg_tms`
FROM `tablename`.`node` AS `n`
WHERE `n`.`display_name` = ('#' + '001')

So that clears thing up a bit. I had assumed Entity Framework would concat the strings before generating the query.

Upvotes: 3

Views: 94

Answers (1)

Svek
Svek

Reputation: 12888

I am going to go ahead and work off the comments, your original question and your findings that you noted as an edit to your post --- and I think the objective was to refactor your original two statements into a single statement.

// code to refactor into a single statement
var nodeDisplayName = ("#" + nodeId);
var filteredNodes = dbContext.Node.Where(n => n.DisplayName == nodeDisplayName).ToList();

This can be refactored to...

// solution (refactored)
var filteredNodes = dbContext.Node.Where(n => n.DisplayName == $"#{nodeId}").ToList();

I had originally noted my answer as a comment, but the new syntax may not have stood out as an answer for you initially. I hope this helps.

Upvotes: 3

Related Questions