Link to home
Start Free TrialLog in
Avatar of malibuboats
malibuboats

asked on

Web Service with nested key collecitions

I'm trying to create a web service that will expose an object with nested key collections.  When I test out the web service I get this error:

System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.ObjectModel.KeyedCollection`2.AddKey(TKey key, TItem item)
   at System.Collections.ObjectModel.KeyedCollection`2.InsertItem(Int32 index, TItem item)
   at System.Collections.ObjectModel.Collection`1.Add(T item)
   at Test.WebServices.ModelService.Test() in C:\Dev 09\Test.WebServices\ModelService.asmx.cs:line 75

I've tested just one key collection and it works great it's when I nest key collections is when it throws the errors.

This is a simplify version of the objects involve and test method I used:
    [WebMethod]
    public Class1 Test()
    {
      Class1 x1 = new Class1();

      Class2 x2 = new Class2();
      testObj y = new testObj();
      for (int i2 = 0; i2 < 5; i2++)
      {
        testObj2 y2 = new testObj2();
        for (int i3 = 0; i3 < 5; i3++)
        {
          y2.ID = i3;
          y2.Value = "test obj " + i3.ToString();
          x2.Add(y2);
        }
        y.ID = i2;
        y.Obj2 = x2;
        x1.Add(y);
      }
      return x1;
    }
  public class Class1 : KeyedCollection<int, testObj>
  {
    protected override int GetKeyForItem(testObj item)
    {
      return item.ID;
    }
  }

  public class Class2 : KeyedCollection<int, testObj2>
  {
    protected override int GetKeyForItem(testObj2 item)
    {
      return item.ID;
    }
  }

  public class testObj
  {
    private int _id;
    private Class2 _obj2;

    public int ID
    {
      get { return _id; }
      set { _id = value; }
    }

    public Class2 Obj2
    {
      get { return _obj2; }
      set { _obj2 = value; }
    }
  }

  public class testObj2
  {
    private int _id;
    private string _value;
    public int ID
    {
      get { return _id; }
      set { _id = value; }
    }

    public string Value
    {
      get { return _value; }
      set { _value = value; }
    }
  }
Avatar of surajguptha
surajguptha
Flag of United States of America image

Make sure all the keys within the keycollection are unique.
ASKER CERTIFIED SOLUTION
Avatar of JimBrandley
JimBrandley
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial