How do I clear tracked entities in entity framework

后端 未结 6 1219
不知归路
不知归路 2020-12-04 20:50

I am running some correction code that runs over a big pile of entities, as it progress its speed decreases, that is because the number of tracked entities in the context in

6条回答
  •  情深已故
    2020-12-04 21:31

    1. Possibility: detach the entry

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

    When you detach the entry the change tracker will stop tracking it (and should result in better performance)

    See: http://msdn.microsoft.com/de-de/library/system.data.entitystate(v=vs.110).aspx

    2. Possibility: work with your own Status field + disconnected contexts

    Maybe you want to control the status of your entity independently so you can use disconnected graphs. Add a property for the entity status and transform this status into the dbContext.Entry(entity).State when performing operations (use a repository to do this)

    public class Foo
    {
        public EntityStatus EntityStatus { get; set; }
    }
    
    public enum EntityStatus
    {
        Unmodified,
        Modified,
        Added
    }
    

    See following link for an example: https://www.safaribooksonline.com/library/view/programming-entity-framework/9781449331825/ch04s06.html

提交回复
热议问题