Fastest Way of Inserting in Entity Framework

前端 未结 30 2180
鱼传尺愫
鱼传尺愫 2020-11-21 05:23

I\'m looking for the fastest way of inserting into Entity Framework.

I\'m asking this because of the scenario where you have an active TransactionScope a

30条回答
  •  时光说笑
    2020-11-21 05:50

    Dispose() context create problems if the entities you Add() rely on other preloaded entities (e.g. navigation properties) in the context

    I use similar concept to keep my context small to achieve the same performance

    But instead of Dispose() the context and recreate, I simply detach the entities that already SaveChanges()

    public void AddAndSave(List entities) where TEntity : class {
    
    const int CommitCount = 1000; //set your own best performance number here
    int currentCount = 0;
    
    while (currentCount < entities.Count())
    {
        //make sure it don't commit more than the entities you have
        int commitCount = CommitCount;
        if ((entities.Count - currentCount) < commitCount)
            commitCount = entities.Count - currentCount;
    
        //e.g. Add entities [ i = 0 to 999, 1000 to 1999, ... , n to n+999... ] to conext
        for (int i = currentCount; i < (currentCount + commitCount); i++)        
            _context.Entry(entities[i]).State = System.Data.EntityState.Added;
            //same as calling _context.Set().Add(entities[i]);       
    
        //commit entities[n to n+999] to database
        _context.SaveChanges();
    
        //detach all entities in the context that committed to database
        //so it won't overload the context
        for (int i = currentCount; i < (currentCount + commitCount); i++)
            _context.Entry(entities[i]).State = System.Data.EntityState.Detached;
    
        currentCount += commitCount;
    } }
    

    wrap it with try catch and TrasactionScope() if you need, not showing them here for keeping the code clean

提交回复
热议问题