EF 4.0 IsAttachedTo extension method and error An object with the same key already exists

前端 未结 2 478
滥情空心
滥情空心 2021-01-27 14:28

I was getting an error

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-27 14:57

    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.

提交回复
热议问题