简体   繁体   中英

How to Configure the Where clause in Entity Framework

I want to make WHERE clause configured in app.config so I followed the below way..

app.config :

<add key="TYPE" value="'Admin','Manager'"/>

Reading it like below:

var types = ConfigurationManager.AppSettings["TYPE"];
var whereClause = types.Replace("'", "\"");

In query:

var data = (from entry in db.TestTable
            where new[] {whereClause}.Contains(entry.Name)
            select new
            {
              Id = entry.Id,
              FirstName = entry.FName,
              LastName = entry.LName   
            }).ToList();

It is not throwing any error also not returning any data.

What I am doing wrong here ? is there any better way to achieve this?

You're searching the string, "Admin", "Manager" for the entry. Tryparsing the app setting into an array?

<add key="TYPE" value="Admin|Manager"/>

Then

var types = ConfigurationManager.AppSettings["TYPE"];
var whereClause = types.Split('|');

Then proceed as before. This should generate SQL like;

select id, firstname, lastname
from testtable
where name in ("Admin", "Manager")

whereClause is a single string. In your example it ends up being the literal string "Admin","Manager" (not TWO strings, but one string including double-quotes and a comma).

You are creating an "array" that consists of that single string and seeing if it "contains" entry.Name . So unless there is an entry whose name is exactly "Admin","Manager" the where clause will return false.

Rather than replacing the single quotes with double quotes split the string and remove the single quotes altogether:

var whereClause = types.Replace("'", "").Split(",");

and change your query to

var data = (from entry in db.TestTable
            where whereClause.Contains(entry.Name)
            select new
            {
              Id = entry.Id,
              FirstName = entry.FName,
              LastName = entry.LName   
            }).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM