Entity Framework and Multi threading

前端 未结 6 595
走了就别回头了
走了就别回头了 2020-12-02 12:26

We are having some trouble designing our multi-threaded Entity Framework driven application and would like some guidance. We are creating entities on different threads, the

6条回答
  •  不思量自难忘°
    2020-12-02 12:42

    I'm using Blazor Server Side with DbContext.

    I've actually done your second way, and it's been working alright. Be careful of untracked entities.

    A DbContext that is scope lived which is an interface that implements IReadOnlyApplicationDbContext that only provides the IQueryable for the DbSets (no SaveChanges or anything like that). So all read operations are safely executed without having the problem of an update messing around with the data.

    Also, all queries use "AsNoTracking" to prevent saving tracks of the last query in cache.

    After that, all write/update/delete updates are made by unique DbContexts.

    It became something like that:

    public interface IReadOnlyApplicationDbContext
    {
        DbSet Products { get; }
    }
    
    public interface IApplicationDbContext : IReadOnlyDbContext
    {
        DbSet Products { set; }
    }
    
    public class ApplicationDbContext : DbContext, IApplicationDbContext
    {
        DbSet Products { get; set; }
    }
    
    public abstract class ProductRepository
    {
        private readonly IReadOnlyApplicationDbContext _readOnlyApplicationDbContext;
        private readonly IFactory _applicationDbContextFactory;
        
        protected Repository(
            IReadOnlyApplicationDbContext readOnlyApplicationDbContext,
            IFactory applicationDbContextFactory
        )
        {
            _readOnlyApplicationDbContext = readOnlyApplicationDbContext;
            _applicationDbContextFactory = _applicationDbContextFactory;
        }
        
        private IQueryable ReadOnlyQuery() => _readOnlyApplicationDbContext.AsNoTracking();
        
        public Task> Get()
        {
            return ReadOnlyQuery().Where(s=>s.SKU == "... some data ...");
        }
        
        public Task Update(Product product)
        {
            using (var db = _applicationDbContextFactory.Create())
            {
                db.Entity(product).State = EntityState.Modified;
                return db.SaveChangesAsync();
            }
        }
        
        public Task Add(Product product)
        {
            using (var db = _applicationDbContextFactory.Create())
            {
                db.Products.AddAsync(product);
                return db.SaveChangesAsync();
            }
        }
    }
    

提交回复
热议问题