Attaching and detaching entities from context correctly in EF4.1

前端 未结 2 2007
难免孤独
难免孤独 2020-12-05 00:27

I am trying to implement caching mechanism for entities. And to use the entities correctly and seamlessly with the caching i need to detach the entity from the current conte

2条回答
  •  没有蜡笔的小新
    2020-12-05 00:50

    IEntityWithKey is interface for other types of entities. It is for "big" entities. For example EntityObject implement this interface. These entities are not considered as POCO and are not supported by DbContext API.

    If you want to use IEntityWithKey your classes must implement it - it is not something that would happen automatically.

    Correct attaching with DbContext API should be:

    dbContext.Set(typeof(entity)).Attach(entity); 
    

    and this should hopefully also work:

    dbContext.Entry(entity).State = EntityState.Unchanged;
    

    Correct detaching with DbContext API should be:

    dbContext.Entry(entity).State = EntityState.Detached;
    

    Also it is better to you generic methods instead of object.

提交回复
热议问题