[Entity Framework Core] How to specify columns with variables in the Where statement [ASP.NET Core]

table of contents
Hello, this is Hase from the System Development Department.
I recently started developing with ASP.NET Core again, and
I was impressed to learn that when retrieving information using Entity Framework Core's Where command, you can dynamically specify column names using variables, so I would like
to introduce it to you.
Preface
First, let's say you have table data like this:
Accounts
| Id | NickName | Last Name | FirstName |
|---|---|---|---|
| 1 | Rena | Hatakeyama | Reina |
| 2 | Toshiaki | Matsuzaki | Shunmyo |
| 3 | Sena | Ishii | Sena |
| 4 | Shozo | Kokura | Shozo |
| 5 | Kotaro | south | Kotaro |
*This is test data extracted from this
I would like to extract records from this data by specifying the columns and values
The usual way
In the normal way, you cannot specify columns dynamically, so the code will look like this:
string columnName = "LastName"; // Column name string value = "Hatayama"; // Search value // Extract records from the specified column name and value var query = context.Accounts; switch (columnName) { // When the NickName column is specified case "NickName": query = query.Where(c => c.NickName== value); break; // When the LastName column is specified case "LastName": query = query.Where(c => c.LastName== value); break; // When the FirstName column is specified case "FirstName": query = query.Where(c => c.FirstName == value); break; } var account = query.FirstOrDefault();
This results in a very redundant code, where each column name is compared with a case in the switch statement
Specifying column names using variables
However, Entity Framework Core has a way to dynamically specify column names!
The EF.Property method is
a great way to dynamically specify properties (column names) as arguments.
If you actually modify the previous code to use this method,
string columnName = "FirstName"; // Column name string value = "Sena"; // Search value // Extract records from the specified column name and value var account = context.Accounts.Where(c => EF.Property<string> (c, columnName) == value).FirstOrDefault();
You can now write it in one line without using a switch statement.
*You need to use Microsoft.Entity Framework Core.
summary
What did you think?
I personally think this is a very useful feature.
I'm sure it will be useful when you want to implement a rich search function, so
please take a look at it when using Entity Framework Core!
lastly
I have opened the system development service site "SEKARAKU Lab" to which I belong.
Beyond is a one-stop service for everything from server design and construction to operation, so if you have any trouble with server-side development, please feel free to contact us.
SEKARAKU Lab: [https://sekarakulab.beyondjapan.com/](https://sekarakulab.beyondjapan.com/)
It's short, but that's all
3