Entity Framework : Sharing entities across different DbContexts

后端 未结 4 1536
后悔当初
后悔当初 2020-12-30 07:12

I\'m developing a plugin application with EF6, code first.

I have one main context with an entity called User:

public class MainDataCont         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 07:46

    When you add the Booking entity, don't use the DbSet.Add() method. Instead use the DbSet.Attach() method and set the DbContext.Entry(Entity).State property for the Booking to EntityState.Added and make sure the DbContext.Entry(Entity).State for User stays EntityState.Unchanged.

    So for example instead of doing this:

    pluginDataContext.dbBooking.Add(myNewBooking);
    

    Do this:

    pluginDataContext.dbBooking.Attach(myNewBooking);
    pluginDataContext.Entry(myNewBooking).State = EntityState.Added;
    

    This is because the Add() method marks all entities in the object graph as EntityState.Added which will cause inserts without checking if the entity already exists in the database. The Attach() method simply makes the context begin tracking the entity.

    This is why I almost never use DbSet.Add().

提交回复
热议问题