Prevent Adding New Record on Related Table Entity in Entity Framework

后端 未结 1 1878
[愿得一人]
[愿得一人] 2021-01-12 16:24

I am trying to add new record on my entity. It works fine, the problem is, the related entities are adding new records as well. Is there a way to stop related or 2nd level e

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 16:44

    You need to set/mark the employee as Unchanged or Attach the entity

    If you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet. The entity will be in the Unchanged state in the context

    context.Employees.Attach(emp); 
    

    Note that no changes will be made to the database if SaveChanges is called without doing any other manipulation of the attached entity. This is because the entity is in the Unchanged state.

    Another way to attach an existing entity to the context is to change its state to Unchanged.

    context.Entry(emp).State = EntityState.Unchanged;
    

    EntityState Enumeration

    Unchanged The object has not been modified since it was attached to the context or since the last time that the SaveChanges method was called.


    Entity Framework Add and Attach and Entity States

    Entity states and SaveChanges

    An entity can be in one of five states as defined by the EntityState enumeration. These states are:

    • Added: the entity is being tracked by the context but does not yet exist in the database
    • Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database
    • Modified: the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified
    • Deleted: the entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called
    • Detached: the entity is not being tracked by the context

    SaveChanges does different things for entities in different states:

    • Unchanged entities are not touched by SaveChanges. Updates are not sent to the database for entities in the Unchanged state.
    • Added entities are inserted into the database and then become Unchanged when SaveChanges returns.
    • Modified entities are updated in the database and then become Unchanged when SaveChanges returns.
    • Deleted entities are deleted from the database and are then detached from the context.

    0 讨论(0)
提交回复
热议问题