bchavez/Bogus · error · ArgumentException

An item with the same key has already been added.

Error message

An item with the same key has already been added.

What it means

Thrown by MultiSetDictionary.Add when a value for a key is already present in that key's HashSet. MultiSetDictionary maps one key to many distinct values; attempting to add a duplicate (key,value) pair is rejected. This is internal infrastructure backing Bogus rule tracking.

Source

Thrown at Source/Bogus/Rule.cs:67

      values[key2] = value;
   }
}

public class MultiSetDictionary<Key, Value> : Dictionary<Key, HashSet<Value>>
{
   public MultiSetDictionary(IEqualityComparer<Key> comparer) : base(comparer)
   {
   }

   public void Add(Key key, Value value)
   {
      if( !this.TryGetValue(key, out var values) )
      {
         values = new HashSet<Value>();
         this.Add(key, values);
      }
      if( values.Contains(value) )
         throw new ArgumentException("An item with the same key has already been added.");
      values.Add(value);
   }
}

View on GitHub (pinned to 6ece18c5c2)

Solutions

  1. Avoid registering duplicate rules for the same member; later rules should replace, check the API you are using.
  2. If extending Bogus internals, check values.Contains(value) before adding.
  3. Review RuleFor/RuleForType call sites for accidental double-registration.

Example fix

// before
f.RuleFor(x => x.Id, _ => 1);
f.RuleFor(x => x.Id, _ => 2); // if routed through multiset
// after
f.RuleFor(x => x.Id, _ => 2); // single registration, or use the override that replaces
Defensive patterns

Strategy: validation

Validate before calling

// internal multiset: check before adding
if (!multiset.TryGetValue(key, out var set) || !set.Contains(value))
    multiset.Add(key, value);

Try / catch

try { dict.Add(key, value); }
catch (ArgumentException ex) when (ex.Message.Contains("same key has already been added")) {
    // skip duplicate or replace existing value
}

Prevention

When it happens

Trigger: Internal: registering the same rule binding (member -> setter) twice within the same MultiSetDictionary instance. Users typically hit it indirectly via duplicate RuleFor registrations on the same member within a context that dedupes.

Common situations: Calling RuleFor on the same property twice in a way that feeds the multiset; custom extensions that push into internal rule storage.

Related errors


AI-assisted analysis of bchavez/Bogus@6ece18c5c2 (2026-08-13). Data as JSON: /api/errors/a281e7716b274ab6. Report an issue: GitHub.