none
AddObject is trying to add my object PLUS related objects (that are already in DB) RRS feed

  • Question

  • (Entity Framework 4.0, with POCO template)

    I adding an object through the data context using the standard approach:

    _model.Products.AddObject(objNewProduct);
    _model.SaveChanges();

    However, the object has a number of related objects attached as properties. For example there is a Category object attached to objNewProduct.

    When SaveChanges() is called, EF attempts to insert a new Category record into the database, but as the category already exists, this is rejected by the database.

    objNewProduct was passed into the application through a web service, rather than being created in code as a new product. I can't do anything about the fact that it has extra objects attached to it. I don't know if this is the source of the problem, or if as a general rule objects being added to the data context should never have related objects attached.

    So, is a better approach to create a new product object, transfer the necessary properties from the passed in object to it, then add it and save changes? Or is there a less laborious option to saving an object from an external source?

    Tuesday, February 14, 2012 7:55 AM

Answers

  • That is how AddObject behaves. If you want ot avoid it you must use Attach instead and change the state of entities you want to insert to Added or probably better option is using AddObject and change state of all existing objects to Unchanged. Simply EF doesn't know which entity is new and which one is existing and you must manually define it by correctly setting the state.

     

    • Proposed as answer by Allen_MSDNModerator Thursday, February 16, 2012 1:53 AM
    • Marked as answer by LaurenceN Thursday, February 16, 2012 9:52 AM
    Tuesday, February 14, 2012 10:10 PM

All replies

  • That is how AddObject behaves. If you want ot avoid it you must use Attach instead and change the state of entities you want to insert to Added or probably better option is using AddObject and change state of all existing objects to Unchanged. Simply EF doesn't know which entity is new and which one is existing and you must manually define it by correctly setting the state.

     

    • Proposed as answer by Allen_MSDNModerator Thursday, February 16, 2012 1:53 AM
    • Marked as answer by LaurenceN Thursday, February 16, 2012 9:52 AM
    Tuesday, February 14, 2012 10:10 PM
  • Thanks. Using AddObject and changing the state of all existing objects to Unchanged sounds like the way to go.
    Thursday, February 16, 2012 9:53 AM