0

I'm trying to use HTTP POST to create a list of new entities on my model.

public HttpResponseMessage Post(int requestId, IEnumerable<Component> components)
{
   Request request = database.Request.Find(requestId);
   foreach(var component in components)
   {
         database.Entry(component.ComponentType).State = EntityState.Unchanged;
         database.Entry(component.SourceResource).State = EntityState.Unchanged;
         database.Entry(component.TargetResource).State = EntityState.Unchanged;
         request.Component.Add(component);
   }
   database.SaveChanges();
   return response;
}

When the components list has only one element it works perfectly, however when it has two or more elements I have the following error message:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code. Additional information: Attaching an entity of type 'AUP.ComponentType' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

How can I add only the fields of the component and keep the references to the ComponentType, SourceResource and TargetResource that already exist in the database?

Ricardo
  • 9
  • 2
  • 1
    You make sure you do not add elements with the same primary key? Did you read the error message? It is extremely clear in why it throws an error. You can not add multiple instances with the same primary key. – TomTom Nov 19 '14 at 10:25
  • components list has a set of components with the same ComponentType, hence the database.Entry(component.ComponentType).State = EntityState.Unchanged to let the database know that the ComponentType already exists and to just add a reference to it. – Ricardo Nov 19 '14 at 10:35

1 Answers1

0

you need to add the references not the id's

think this can help you stack overflow

Community
  • 1
  • 1
Pranay Dutta
  • 2,483
  • 2
  • 30
  • 42