如何在C#中动态创建FileUploads的查询?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在C#中动态创建FileUploads的查询?相关的知识,希望对你有一定的参考价值。
如何减少下面代码中的代码冗余?我正在尝试根据上传的动态附件数量构建查询。用户最多可以添加5个附件。程序需要根据输入附件的数量检查查询并构建查询。示例代码如下所示:
StringBuilder sbView5SaveQuery = new StringBuilder();
sbView5SaveQuery.Append("update Master set ");
if (FileUpload1.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc1 = @SupportDoc1");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc1 = @CanPublishDoc1");
sbView5SaveQuery.Append(" ");
}
if (FileUpload2.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc2 = @SupportDoc2");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc2 = @CanPublishDoc2");
sbView5SaveQuery.Append(" ");
}
if (FileUpload3.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc3 = @SupportDoc3");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc3 = @CanPublishDoc3");
sbView5SaveQuery.Append(" "); ;
}
if (FileUpload4.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc4 = @SupportDoc4");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc4 = @CanPublishDoc4");
sbView5SaveQuery.Append(" ");
}
if (FileUpload5.HasFile)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("SupportDoc5 = @SupportDoc5");
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append("CanPublishDoc5 = @CanPublishDoc5");
sbView5SaveQuery.Append(" ");
}
sbView5SaveQuery.Append("where MasterID = @MasterID");
答案
在类中创建一个方法并将值传递给它,而不是重复每次上传的代码:
public class MyClass
{
private StringBuilder sbView5SaveQuery;
private void BuildQuery(string supportDoc, string canPublishDoc)
{
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append(supportDoc + " = @" + supportDoc);
sbView5SaveQuery.Append(",");
sbView5SaveQuery.Append(canPublishDoc + " = @" + canPublishDoc);
sbView5SaveQuery.Append(" ");
}
public string MyMethod()
{
sbView5SaveQuery = new StringBuilder();
sbView5SaveQuery.Append("update Master set ");
if (FileUpload1.HasFile)
{
BuildQuery("SupportDoc1", "CanPublishDoc1");
}
if (FileUpload2.HasFile)
{
BuildQuery("SupportDoc2", "CanPublishDoc2");
}
// and so one...
return sbView5SaveQuery.ToString();
}
}
以上是关于如何在C#中动态创建FileUploads的查询?的主要内容,如果未能解决你的问题,请参考以下文章