[Entity Framework Core] How to specify columns with variables in the Where statement [ASP.NET Core]
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 you can dynamically specify column names using variables when retrieving information using Where in Entity Framework Core, so I
'd like to introduce it to you. I'll have it.
Preface
First, let's say you have table data like the following.
Accounts
Id | NickName | LastName | FirstName |
---|---|---|---|
1 | Rena | Hatakeyama | Reina |
2 | Toshiaki | Matsuzaki | Toshiaki |
3 | Sena | Ishii | Sena |
4 | Shozo | Kokura | Shozo |
5 | Kotaro | south | Kotaro |
*This is test data and was extracted from this
I would like to extract records from this data by specifying each column and value.
normal way
In the normal way, columns cannot be specified dynamically in the first place, so the code will be as follows.
string columnName = "LastName"; // Column name string value = "Hatakeyama"; // Search value // Extract records from the specified column name and value var query = context.Accounts; switch (columnName) { // NickName If you specify a column case "NickName": query = query.Where(c => c.NickName== value); break; // If you specify a LastName column case "LastName": query = query.Where(c = > c.LastName== value); break; // If you specify the FirstName column case "FirstName": query = query.Where(c => c.FirstName == value); break; } var account = query.FirstOrDefault ();
This results in quite redundant code, as each column name is compared using a case in a switch statement.
How to specify column names with variables
However, Entity Framework Core has a way to dynamically specify column names!
That's called
the EF.Property method This is an excellent feature that allows you to dynamically specify properties (column names) using arguments.
If you actually modify the code above to use this method,
string columnName = "FirstName"; // Column name string value = "Sena"; // Search value // Extract records from 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 must use Microsoft.Entity Framework Core.
summary
What did you think?
Personally, I thought it was a very useful feature.
I'm sure it will be useful when you want to implement rich search functionality, so
please use it as a reference 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 it.