Exemple #1
0
        /// <summary>
        /// Responsible for creating a new dbContext with given <see cref="DbContextOption.Mode"/>
        /// </summary>
        /// <typeparam name="T">dbContext of type {T} to be created.</typeparam>
        /// <param name="mode"><see cref="DbContextOption.Mode"/> to create dbContext with.</param>
        /// <param name="isolationLevel"><see cref="IsolationLevel"/> to create dbContext with.</param>
        /// <param name="dbTransaction">create a dbContext with external transaction</param>
        /// <param name="sqlConnection">create a dbContext with existing sql connection</param>
        /// <returns>true if new dbContext created else false.</returns>
        internal bool CreateNewDbContextIfNotExists <T>(DbContextOption.Mode mode, IsolationLevel?isolationLevel, DbTransaction dbTransaction, DbConnection sqlConnection) where T : DbContext, IAmbientDbContext, new()
        {
            if (DbContextCollection.GetDbContextByType <T>() != null)
            {
                return(false);
            }
            //Creating a new DbContext Type
            T currentDbContext;

            if (dbTransaction != null && sqlConnection != null)
            {
                currentDbContext = Activator.CreateInstance(typeof(T), sqlConnection, false) as T;
            }
            else
            {
                currentDbContext = Activator.CreateInstance(typeof(T)) as T;
            }

            if (currentDbContext != null)
            {
                currentDbContext.Mode = mode;

                if (mode == DbContextOption.Mode.Read)
                {
                    currentDbContext.Configuration.AutoDetectChangesEnabled = false;
                }
                if (dbTransaction != null)
                {
                    currentDbContext.Database.UseTransaction(dbTransaction);
                    DbContextCollection.Add(currentDbContext, null);
                }
                else
                {
                    if (isolationLevel.HasValue)
                    {
                        IsolationLevel = isolationLevel.Value;
                        var transaction = currentDbContext.Database.BeginTransaction(isolationLevel.Value);
                        DbContextCollection.Add(currentDbContext, transaction);
                    }
                    else
                    {
                        var transaction = currentDbContext.Database.BeginTransaction();
                        DbContextCollection.Add(currentDbContext, transaction);
                    }
                }
            }
            return(true);
        }
Exemple #2
0
 internal T GetDbContextByType <T>() where T : DbContext, IAmbientDbContext, new()
 {
     return(DbContextCollection.GetDbContextByType <T>());
 }