且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架错误 - 同时读取数据库

更新时间:2022-11-04 21:11:27

我这样做与IOC /依赖关系注入以及传递到每个库一个单DatabaseFactory。该DatabaseFactory类持有该网站的唯一的DbContext,这样一来,只有一个,不进入任何奇怪的问题。而且我也注入我的仓库到我的控制器..我只是懒惰这样。

I do this with IoC/Dependancy Injection and a singleton DatabaseFactory that gets passed into each repository. The DatabaseFactory class holds the only DbContext for the site, this way there is only one and don't get into any weird issues. And I also inject my repositories into my controllers.. I'm just lazy like that.

DatabaseFactory

DatabaseFactory

public class DatabaseFactory : Disposable, IDatabaseFactory
{
    private CragDbContext _dataContext;
    private string _connectionString;

    public string ConnectionString
    {
        get { return _connectionString; }
        set { _connectionString = value; }
    }

    public DatabaseFactory(string connectionString)
    {
        if (connectionString == null) 
            throw new ArgumentNullException("connectionString");

        _connectionString = connectionString;
    }

    public CragDbContext Get()
    {
        if (string.IsNullOrEmpty(_connectionString))
            return _dataContext ?? (_dataContext = new CragDbContext());


        return _dataContext ?? (_dataContext = new CragDbContext(_connectionString));
    }

    protected override void DisposeCore()
    {
        if (_dataContext != null)
            _dataContext.Dispose();
    }
}

BaseRepository(我所有的respositories继承)

BaseRepository (that all my respositories inherit from)

public class BaseRepository<T> : IRepository<T> where T : BaseEntity
{
    protected CragDbContext DbContext;
    protected readonly IDbSet<T> DbSet;

    protected IDatabaseFactory DatabaseFactory { get; private set; }

    protected CragDbContext Context
    {
        get { return DbContext ?? (DbContext = DatabaseFactory.Get()); }
    }

    #region Ctor

    public BaseRepository(IDatabaseFactory databaseFactory)
    {
        if (databaseFactory == null) 
            throw new ArgumentNullException("databaseFactory");

        DatabaseFactory = databaseFactory;
        DbSet = Context.Set<T>();
    }

    #endregion

    public virtual void Add(T entity)
    {
        DbSet.Add(entity);
    }

    .... etc
}

其实,我在中间的UnitOfWork类,但你可以不用的。希望这有助于。

I actually have a UnitOfWork class in the middle, but you can do it without that. Hope this helps.