简体   繁体   English

用C#编写基于用户输入条件的动态sql查询

[英]writing dynamic sql query based on user input coditions in C#

CREATE TABLE [DBO].[TBL_PROFILE] 
(
    PROFILE_ID BIGINT IDENTITY(1, 1) NOT NULL
    ,NAME NVARCHAR(200) NOT NULL
    ,GENDER TINYINT NOT NULL
    ,CASTE NVARCHAR(15)
    ,QUALIFICATION NVARCHAR(50)
    ,COMPLEXION NVARCHAR(50)
    ,FEEDING_HBTS INT 
    ,CONSTRAINT PK__PROFILE PRIMARY KEY (PROFILE_ID)
)

INSERT INTO [DBO].[TBL_PROFILE] 
VALUES ('AJAY', 1, 'BRAHMAN', 'MASTER', 'FAIR', 1),
       ('JIRAM', 1, 'CHETTRI', 'BACHELOR', 'BLACK', 1),
       ('SUMAN', 1, 'NEWAR', '+2', 'BLACK', 1),
       ('HIRA', 1, 'MAGAR', 'BACHELOR', 'FAIR', 1),
       ('JANNY', 1, 'MAGAR', 'BACHELOR', 'MEDIUM', 1),
       ('RANVI', 1, 'NEWAR', 'BACHELOR', 'BLACK', 1),
       ('SURAJ', 1, 'BRAHMAN', 'BACHELOR', 'FAIR', 1);

Above is the SQL Server table and some sample data for testing purpose.以上是用于测试目的的 SQL Server 表和一些示例数据。

In the front end, the user has the option to select the caste, qualification, complexion and based on these conditions I've to design the query.在前端,用户可以选择种姓、资格、肤色,并根据这些条件设计查询。 The user can select more than one value for any of these attributes.用户可以为这些属性中的任何一个选择多个值。 Now based on these user conditions, I've to design the sql query in C#.现在基于这些用户条件,我必须在 C# 中设计 sql 查询。

Suppose, the user selects NEWAR, MAGAR as caste and others are NULL, then the query would be:假设,用户选择 NEWAR,MAGAR 作为种姓,其他人为 NULL,那么查询将是:

SELECT * 
FROM [DBO].[TBL_PROFILE] 
WHERE GENDER = 1
  AND CASTE IN ('NEWAR', 'MAGAR')

Suppose the user selects qualification as BACHELOR and COMPLEXION as FAIR, BLACK then the query would be:假设用户选择资格为 BACHELOR 和 COMPLEXION 为 FAIR, BLACK 那么查询将是:

SELECT * 
FROM [DBO].[TBL_PROFILE] 
WHERE GENDER = 1
  AND COMPLEXION IN ('FAIR', 'BLACK') 
  AND QUALIFICATION = 'BACHELOR';

So the query is dynamic, based on the three attributes.所以查询是动态的,基于三个属性。 How can I write dynamic query in C# for this scenario?对于这种情况,如何在 C# 中编写动态查询?

There are literally 100s of ways to do this.有数百种方法可以做到这一点。

In the old days we would just use if statements and a StringBuilder .在过去,我们只会使用if语句和StringBuilder These days ORMs Like Entity Framework are commonly used, and a very successful at solving problems like this.如今,实体框架这样的ORM被普遍使用,并且在解决此类问题方面非常成功。

However, if you don't want to spin up your own query, or use an ORM like Entity Framework , I'll suggest a query builder.但是,如果您不想启动自己的查询,或者不想使用Entity Framework 之类的 ORM,我会建议使用查询构建器。 Once again these are dime-a-dozen, and there are hundreds of them.再一次,这些是一毛钱,而且有数百个。 A quick web search found https://sqlkata.com/docs/快速网络搜索发现https://sqlkata.com/docs/

  • Install-Package SqlKata安装包 SqlKata
  • Install-Package SqlKata.Execution安装包 SqlKata.Execution

Code代码

// these would come from the ui
int? gender = 1;
var complexion = new[]
                     {
                        "FAIR",
                        "BLACK"
                     };
var qualification = "BACHELOR";

// setup
var connection = new SqlConnection("...");
var compiler = new SqlServerCompiler();
var db = new QueryFactory(connection, compiler);

//query
var query = db.Query("TBL_PROFILE");

if (gender != null)
   query.Where("GENDER", gender);

if (complexion != null)
   query.WhereIn("COMPLEXION ", complexion);

if (qualification != null)
   query.Where("QUALIFICATION ", qualification);

...

var results = query.Get();

foreach (var profile in results)
{
   Console.WriteLine($"{profile.Id}: {profile.Name}");
}

Disclaimer : I'm not endorsing this query builder and I have never used it.免责声明:我不认可这个查询构建器,我从未使用过它。 You need to do your own due diligence and use at your own risk .您需要自己进行尽职调查并自行承担使用风险

Personally I'd recommend just jumping in the deep-end and use Entity Framework and be done with it.我个人建议直接跳入深层并使用实体框架并完成它。 However, this example might get your pointed in the right direction.但是,这个例子可能会让你指出正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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