private void DeleteDatabase <TDbContext>() where TDbContext : MyTestContext, new()
 {
     using (TDbContext context = new TDbContext())
     {
         context.Database.EnsureDeleted();
     }
 }
Пример #2
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="forWriting">Is the root context opened for writing?</param>
 public ScopedDbContext(bool forWriting)
 {
     ForWriting = forWriting;
     DbContext  = new TDbContext();
     ((IObjectContextAdapter)DbContext).ObjectContext.SavingChanges
         += GuardAgainstDirectSaves;
 }
 public static Func <TEntity, PrimaryKeyDictionary <TEntity> > GetFunc <TDbContext, TEntity>() where TEntity : class where TDbContext : DbContext, new()
 {
     return(PerDbContextTypeCache <TEntity> .Map.GetOrAdd(typeof(TDbContext),
                                                          type => {
         using (var context = new TDbContext())
             return GetFunc <TEntity>(context);
     }));
 }
Пример #4
0
 /// <summary>
 /// Initialize a new instance of the <see cref="EfDbContextManager"/> class.
 /// </summary>
 /// <param name="args">The <see cref="IEfDbArgs"/>.</param>
 public EfDbContextManager(IEfDbArgs args)
 {
     if (args != null && args.DbContext != null)
     {
         DbContext = (TDbContext)args.DbContext;
     }
     else
     {
         _closeAndDispose = true;
         DbContext        = new TDbContext();
     }
 }
        /// <summary>
        /// 线程级 缓存 数据库
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static TDbContext CurrentDbContext <TDbContext>() where TDbContext : DbContext, new()
        {
            var name = typeof(TDbContext).FullName;
            var db   = CallContext.GetData(name) as TDbContext;

            if (db == null)
            {
                db = new TDbContext();
                CallContext.SetData(name, db);
            }
            return(db);
        }
        private IContext GetContext(ITypesResolver typesResolver)
        {
            var optionsBuilder = new DbContextOptionsBuilder <TDbContext <IdentityUser, IdentityRole, string> >();

            optionsBuilder.UseInMemoryDatabase("NlayerappDb");

            var context = new TDbContext <IdentityUser, IdentityRole, string>(optionsBuilder.Options, typesResolver);

            ((DbContext)context).Database.EnsureCreated();
            // ((DbContext)context).Database.Migrate();
            return(context);
        }
Пример #7
0
        public static DbContext CreateDbContext <TDbContext>() where TDbContext : DbContext, new()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("DatabaseConnectionString");
            }

            TDbContext context = new TDbContext();

            context.Database.Connection.ConnectionString = connectionString;
            return(context);
        }
Пример #8
0
        public override TDbContext GetDbContext <TDbContext>()
        {
            TDbContext value = default(TDbContext);

            foreach (var item in ActiveDbContexts.Values)
            {
                if (item.GetType() == typeof(TDbContext))
                {
                    value = item as TDbContext;
                    break;
                }
            }
            return(value);
        }
Пример #9
0
        public TDbContext GetOrCreateDbContext <TDbContext>() where TDbContext : DbContext
        {
            Type      contextType = typeof(TDbContext);
            string    contextKey  = contextType.FullName;
            DbContext context     = null;

            if (ActiveDbContexts.TryGetValue(contextKey, out context))
            {
                return((TDbContext)context);
            }

            TDbContext dbContext = IocManager.Instance.Resolve <TDbContext>();

            if (dbContext.IsNotNull())
            {
                ActiveDbContexts.Add(contextKey, dbContext);
            }
            return(dbContext);
        }
Пример #10
0
        public TDbContext Current <TDbContext>() where TDbContext : DbContext, new()
        {
            DbContext item = null;

            if (_dbContexts.ContainsKey(typeof(TDbContext)))
            {
                _dbContexts.TryGetValue(typeof(TDbContext), out item);
            }
            if (item != null)
            {
                return((TDbContext)item);
            }
            _dbContexts.Remove(typeof(TDbContext));

            item = new TDbContext();
            _dbContexts.Add(item.GetType(), item);
            OnDbContextCreated(item);
            return((TDbContext)item);
        }
        // Automatische Generierung aus DbContext-Klasse
        public static IEnumerable <Tabledefinition> CreateFromDbContext <TDbContext>()
            where TDbContext : DbContext, new()
        {
            using (var ctx = new TDbContext())
            {
                var type = typeof(TDbContext);

                // Alle Properties der Kontextklasse, die vom Typ DbSet<> sind
                var dbsets = type.GetProperties()
                             .Where(t => t.PropertyType.IsGenericType &&
                                    t.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>));

                var tds = new List <Tabledefinition>();

                // Alle DbSets bearbeiten
                foreach (var p in dbsets)
                {
                    // Typ der Model-Klasse
                    var pt = p.PropertyType.GenericTypeArguments[0];

                    // Metadaten für Model-Klasse anlegen
                    var td = new Tabledefinition
                    {
                        Name                = p.Name,
                        Typename            = p.PropertyType.GenericTypeArguments[0].Name,
                        Url                 = p.Name,
                        PropertyDescriptors = AngularPropertyDescriptionGenerator
                                              .GetAngularPropertyDescriptionForType(pt, ctx)
                                              .OrderBy(pd => pd.Order)
                                              .ToList()
                    };

                    // Primärschlüssel ermitteln
                    var et = ctx.Model.FindEntityType(pt);
                    var pk = et.FindPrimaryKey();
                    td.PrimaryKey = pk?.Properties.FirstOrDefault()?.Name.ToCamelCase();

                    tds.Add(td);
                }
                return(tds);
            }
        }
Пример #12
0
        public NamedMongoDbContext Get <TDbContext>() where TDbContext : NamedMongoDbContext, new()
        {
            var typeKey = typeof(TDbContext);
            NamedMongoDbContext dbContext = null;

            if (_contextDic.ContainsKey(typeKey))
            {
                _contextDic.TryGetValue(typeKey, out dbContext);
            }
            if (dbContext == null)
            {
                _contextDic.TryRemove(typeKey, out dbContext);
            }
            else
            {
                return(dbContext);
            }

            dbContext = new TDbContext();
            _contextDic.TryAdd(typeKey, dbContext);
            return(dbContext);
        }
Пример #13
0
        public TDbContext Get <TDbContext>() where TDbContext : class, IDbContext
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("DbContextCollection");
            }

            Type requestedType = typeof(TDbContext);

            if (!_initializedDbContexts.ContainsKey(requestedType))
            {
                // First time we've been asked for this particular DbContext type.
                // Create one, cache it and start its database transaction if needed.
                TDbContext dbContext = _dbContextFactory != null
                    ? _dbContextFactory.CreateDbContext <TDbContext>()
                    : Activator.CreateInstance <TDbContext>();

                _initializedDbContexts.Add(requestedType, dbContext);

#if NETCOREAPP1_1
                dbContext.ChangeTracker.AutoDetectChangesEnabled = !_readOnly;
#elif EF6
                dbContext.Configuration.AutoDetectChangesEnabled = !_readOnly;
#endif

                if (_isolationLevel.HasValue)
                {
#if NETCOREAPP1_1
                    IDbContextTransaction tran = dbContext.Database.BeginTransaction(_isolationLevel.Value);
#elif EF6
                    DbContextTransaction tran = dbContext.Database.BeginTransaction(_isolationLevel.Value);
#endif
                    _transactions.Add(dbContext, tran);
                }
            }

            return(_initializedDbContexts[requestedType] as TDbContext);
        }
Пример #14
0
        private static TDbContext InnerGetDbContext <TDbContext>() where TDbContext : DbContext, new()
        {
            if (System.Web.HttpContext.Current == null)
            {
                return(null);
            }
            IDictionary items   = System.Web.HttpContext.Current.Items;
            string      keyName = typeof(TDbContext).FullName;

            if (items[HostDbContext] == null)
            {
                TDbContext db = CreateDbContext <TDbContext>(items, new Dictionary <string, DbContext>(), keyName);
                return(db);
            }
            IDictionary dicDbContext = items[HostDbContext] as Dictionary <string, DbContext>;

            if (!dicDbContext.Contains(keyName))
            {
                TDbContext db = CreateDbContext <TDbContext>(items, dicDbContext, keyName);
                return(db);
            }
            return(dicDbContext[keyName] as TDbContext);
        }
Пример #15
0
 public Authentication(IOptions <AuthenticationConfig.Authentication> appSettings,
                       TDbContext context)
 {
     this.appSettings = appSettings.Value;
     this.context     = context;
 }