In Entity Framework, what is the difference between Add and Attach and how can I solve my problem?

后端 未结 2 988
面向向阳花
面向向阳花 2021-02-13 01:02

I recently started using Entity Framework, and it has been kind of a pain to check if I really need to add new records to the database or not.

If the Entity I n

相关标签:
2条回答
  • 2021-02-13 01:24

    I know that I am a little late to this post, but was looking for similar solution... and then I found this Microsoft article which may succinctly answers most of the OP's questions, and may help future SO viewers?:

    Add/Attach and Entity States == ( http://msdn.microsoft.com/en-us/data/jj592676.aspx )

    From the article:

    This topic will cover how to add and attach entities to a context and how Entity Framework processes these during SaveChanges.

    And specifically see the last section on that page:

    Insert or update pattern: A common pattern for some applications is to either Add an entity as new (resulting in a database insert) or Attach an entity as existing and mark it as modified (resulting in a database update) depending on the value of the primary key.

    0 讨论(0)
  • 2021-02-13 01:26

    ObjectContext internally tracks all entities which was either loaded by context, attached or added. Only these entities can be modified in database when SaveChanges is invoked. Each such entity has a ObjectStateEntry in the ObjectStateManager. One of the main properties of the ObjectStateEntry is a State. The state is of enum type EntityState which offers these values:

    • Added
    • Deleted
    • Detached
    • Modified
    • Unchanged

    Each entity loaded from the database is in Unchanged state. Detached is special state. You will not find ObjectStateEntry with Detached state in the ObjectStateManager. But if you ask ObjectStateManager for the ObjectStateEntry for entity not tracked by the context it will create a new ObjectStateEntry with Detached state.

    Now the difference between Attach and AddObject:

    • Attach - if you call this method ObjectContext will start tracking whole object graph (main entity and all related entities). All entities which were not tracked yet will be set to Unchanged state.
    • AddObject - if you call this method ObjectContext will also start tracking whole object graph (main entity and all related entities). The difference is that all entities which were not tracked yet will be set to Added state (= new objects which must be set to database).
    0 讨论(0)
提交回复
热议问题