I was getting an error
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with
It's likely that IsAttachedTo
does not compare by the key (Id
) but by object identity. Because you create a new Subscription
for every item in the loop the objects are all different instances.
Since you seem to have objects with same Id
in your types
collection but in the end only want to add one object per key into the context you can perhaps make your life easier by filtering out the duplicates in the first place:
var distinctTypes = types.Distinct();
foreach (string s in distinctTypes)
{
Subscription subscription = new Subscription { Id = Int32.Parse(s) };
service.repository._context.AttachTo("Subscriptions", subscription);
horse.Subscriptions.Add(subscription);
}
This way there should be only one object per key which gets attached to the context.