Valentin Hrg Valentin Hrg - 3 months ago 27
SQL Question

C# - "An element with the same key was already added"

I work in ASP.NET MVC and I am blocked(surrounded) in my model with this damned error "an element with the same key was already added", I understand not at all why while I have almost the same code with different requests in other methods of my model.

And I do not think that the problem can come from the request because I have already used her(it) as before in another project.

public Dictionary<string,string> getDonnee()
Dictionary<string, string> list = new Dictionary<string, string>();

SqlConnection cn;
SqlDataAdapter da;
DataSet ds;

cn = new SqlConnection(CS_DW);

da = new SqlDataAdapter("select distinct(ltrim(rtrim(cpic))) as code, cpic as lib from [DW].[dbo].[PIC_PROD_S001] ", cn);
ds = new DataSet();
da.Fill(ds, "code");

list.Add("REEL", "REEL");
foreach (DataRow row in ds.Tables["code"].Rows)
list.Add(row["code"].ToString(), row["lib"].ToString());

return list;


Maybe you can test if they key in already in your dictionary

if (!list.ContainsKey(row["code"].ToString())) 
    list.Add(row["code"].ToString(), row["lib"].ToString());