我正在使用C# ASP.NET并计划创建一个需要5个参数作为搜索条件的搜索函数--让我们使用3个条件来制作这个示例: a、b和c
问:我是否需要让所有7种可能的搜索功能:
直接连接到数据库(SQL)
或者,是否可以从数据库(SQL)创建表列表,并在C# aspx.cs中创建一个条件?
我不想问示例代码,我只是想要一个概念来简化我对搜索函数的编码,因为我至少有5个条件,这至少会让我对搜索的所有可能性进行25种不同的搜索功能。谢谢。
发布于 2017-05-02 04:17:14
可以从数据库(SQL)进行操作,这将是最好的解决方案。您必须为此创建如下所示的Stored Procedure。
SQL:
Create Proc SP_Search(@A Int, @B NVarChar(20), @C Int)
As
Begin
If @A = 0 Set @A = Null
If @B = '' Set @B = Null
If @C = 0 Set @C = Null
Select * From Table Where (A=@A Or @A Is Null) And (B=@B Or @B Is Null) And (C=@C Or @C Is Null)
End让我解释一下上面的SQL。它将接受param @A、@B和@C的输入。如果@A是0,那么设置@A = Null。在(A=@A Or @A Is Null)条件下,像可选的param一样工作。如果@A具有某些值,则条件将应用,如果它为null,则条件将忽略。你可以添加更多这样的对词。
Exec SP_Search 1,'',0搜索结果Exec SP_Search 1,'A',0Exec SP_Search 1,'A',1Exec SP_Search 1,'',1Exec SP_Search 0,'A',0Exec SP_Search 0,'A',1Exec SP_Search 0,'',1C#代码调用Stored Procedure
int A = 1;
string B = "A";
int C = 1;
using (SqlConnection conn = new SqlConnection("Connection String")) {
conn.Open();
SqlCommand cmd = new SqlCommand("SP_Search", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@A", A));
cmd.Parameters.Add(new SqlParameter("@B", B));
cmd.Parameters.Add(new SqlParameter("@C", C));
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read())
{
//Read Your Data Here
}
}
}发布于 2017-05-02 04:09:48
不,对于所有可能的组合,您不需要一些特殊的功能。而且,这将是一个非常多的功能。
您只需检查要指定的某些条件并添加此条件即可。
就像这样:
public YourEntity[] Search(string name = "", int? age = null, bool? isActive = null)
{
string query = "SELECT * FROM YourEntities";
List<string> whereConditions = new List<string>();
if (!string.IsNullOrWhiteSpace(name))
{
whereConditions.Add($"name LIKE '%{name}%'");
}
if (age.HasValue)
{
whereConditions.Add($"age = {age.Value}");
}
if (isActive.HasValue)
{
whereConditions.Add($"isActive = {isActive.Value:D}");
}
if (whereConditions.Any())
{
query += "WHERE " + string.Join(" AND ", whereConditions);
}
return someSqlExecutorAndProcessor(query);
}然后,您可以这样使用这个方法:
var results = Search(); // all
var results = Search("name"); // name only
var results = Search(age: 17); // age only
var results = Search("name", isActive: true); // name and isActive重要注意事项:注意到此代码使用字符串连接来构建查询,这是不安全的,它只是提供通用思想的一个最小示例。我只是不知道你用什么处理数据库。使用参数化查询或ORM代替。
例如,如果使用实体框架,则如下所示:
public YourEntity[] Search(string name = "", int? age = null, bool? isActive = null)
{
IQueryable<YourEntity> entities = dbContext.Set<YourEntity>();
if (!string.IsNullOrWhiteSpace(name))
{
entities = entities.Where(x => x.Name.Contains(name));
}
if (age.HasValue)
{
entities = entities.Where(x => x.Age == age.Value);
}
if (isActive.HasValue)
{
entities = entities.Where(x => x.IsActive == isActive.Value);
}
return entities.ToArray();
}https://stackoverflow.com/questions/43729884
复制相似问题