3

I am analyse and making windows service application.

When I make Insert query, I add the columns using List<SqlParameter> and AddRange.

In List<SqlParameter> pmlist = new List<SqlParameter>(keys); line, it contains {@DeptCode}.

Then pmlist.AddRange(pms); line, pms parameters added.

Bus I mentioned earlier pmslist already has {@DeptCode}, so pmlist have a value like this

 pmlist = [0] {@DeptCode} [1] {@DeptCode} [2] {@DeptName}  
 [3] {@ParentDeptName} [4] {@ParentDeptCode} [5] {@DeptLevel}

DeptCode is duplicated. So, it tries to insert query to ShadowDeptTable,

it also has 5 columns, Sql Exception was occurred.

How can I remove or not to get duplicate value? Please help me...

code is below.

//table : ShadowDeptTable ,  keys = {@DeptCode}, 
//pms =   [0] {@DeptCode} [1] {@DeptName} [2] {@ParentDeptName}  
//        [3] {@ParentDeptCode} [4] {@DeptLevel}    

public static int InsertOrUpdate(string table, SqlParameter[] keys, params SqlParameter[] pms)
{
   int st = 0;
   string constr = Util.GetPropVal(Words.PropConnectionString);
   var obj = SqlHelper.ExecuteScalar(constr,CommandType.Text,sb.ToString(),keys);
   StringBuilder sb=new StringBuilder();
   sb = sb.Append("insert into " + table + "(");
   //columns
   string cols = null;
   //values
   string vals = null;
   List<SqlParameter> pmlist = new List<SqlParameter>(keys);
   pmlist.AddRange(pms);
   cols = string.Join(",", pmlist.Select(a => "["+a.ParameterName.Substring(1, a.ParameterName.Length-1)+"]"));
   vals = string.Join(",", pmlist.Select(a => "'" + a.Value + "'"));
   sb = sb.Append(cols);
   sb = sb.Append(") values(");
   sb = sb.Append(vals);
   sb = sb.Append(")");
   obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());
   return Convert.ToInt32(obj);
}
Ryden Choi
  • 307
  • 4
  • 19

2 Answers2

3

I didn't dig into your code to much. Let's say that we just talking about removing duplicates.

If you want to remove duplicates by parameter name maybe you can try this:

var merged = keys.Union(pms).GroupBy(p => p.ParameterName).Select(e => e.First());

It will merge both arrays, group by parameter name and then select the first item from each group.

kat1330
  • 5,134
  • 7
  • 38
  • 61
0

Try to use Except

List<SqlParameter> newPms = pms.Except(pmlist).ToList();
pmlist.AddRange(newPms);
GSP
  • 574
  • 3
  • 7
  • 34
  • Thank you for your advice GSP! – Ryden Choi Feb 17 '17 at 05:17
  • Not sure that will be applicable for this case without implemented comparer. `Except()` uses default comparer and `SqlParameter` is reference type. If objects do not have same references method will consider as different even if they hold same values. – kat1330 Feb 17 '17 at 09:34