Esempio n. 1
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = Speedy.Extensions.GetSerializerSettings(true, false);
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
            GlobalConfiguration.Configuration.EnsureInitialized();

            Database.SetInitializer(new MigrateDatabaseToLatestVersion <ScribeSqlDatabase, Configuration>(true));

            var appDataPath = HttpContext.Current.Server.MapPath("~/App_Data");
            var client      = new ScribeDataChannel(new ScribeDatabaseProvider(() => new ScribeSqlDatabase()));
            var provider    = new KeyValueRepositoryProvider <Event>(appDataPath);

            Tracker = Tracker.Start(client, provider);

            using (var datacontext = new ScribeSqlDatabase())
            {
                var siteSettings = SiteSettings.Load(datacontext);

                IsConfigured = datacontext.Users.Any();
                PrintCss     = siteSettings.PrintCss ?? string.Empty;
                ViewCss      = siteSettings.ViewCss ?? string.Empty;
            }
        }
        /// <summary>
        /// 获取表示与当前 <see cref="DbProviderFactory"/> 关联的数据库提供程序名称。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <returns>表示与当前 <see cref="DbProviderFactory"/> 关联的数据库提供程序名称。</returns>
        public static string GetProviderName(this System.Data.Entity.Database database)
        {
            DbProviderFactory factory      = GetDbProviderFactory(database);
            string            providerName = factory.GetProviderName();

            return(providerName);
        }
        /// <summary>
        /// 获取表示与当前 <see cref="DbProviderFactory"/> 关联的 <see cref="IScriptParameterParser"/> 对象。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <returns>表示与当前 <see cref="DbProviderFactory"/> 关联的 <see cref="IScriptParameterParser"/> 对象。</returns>
        public static DbScriptParameterParser GetDbScriptParameterParser(this System.Data.Entity.Database database)
        {
            string providerName            = GetProviderName(database);
            DbScriptParameterParser parser = DbScriptParameterParser.GetScriptParameterParser(providerName);

            return(parser);
        }
        private static void DropDb(System.Data.Entity.Database databaseContext, string databaseName)
        {
            string sql = $@"
                ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                DROP DATABASE [{databaseName}];";

            databaseContext.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql);
        }
        /// <summary>
        /// 返回当前 <paramref name="database"/> 所使用的 <see cref="DbProviderFactory"/> 工厂对象。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <returns>当前 <paramref name="database"/> 所使用的 <see cref="DbProviderFactory"/> 工厂对象。</returns>
        public static DbProviderFactory GetDbProviderFactory(this System.Data.Entity.Database database)
        {
            Check.NotNull(database);
            DbConnection      connection = database.Connection;
            DbProviderFactory factory    = DbProviderFactories.GetFactory(connection);

            return(factory);
        }
Esempio n. 6
0
 /// <summary>
 /// 使用给定的参数执行给定的查询;
 /// .Net472 下类型为 DbRawSqlQuery
 /// .coreapp 下类型为 IQueryable,
 /// 使用2者向上的公共类型 IEnumerable
 /// </summary>
 public static IEnumerable <T> SqlQuery <T>(this DatabaseFacade database, string sql, params object[] parameters)
     where T : class
 {
     using (var db2 = new ContextForQueryType <T>(database.GetDbConnection()))
     {
         return(db2.Query <T>().FromSql(sql, parameters));
     }
 }
        /// <summary>
        /// 动态查询主方法
        /// </summary>
        /// <returns></returns>
        public static IEnumerable SqlQueryForDynamic(this System.Data.Entity.Database db,
                                                     string sql,
                                                     params object[] parameters)
        {
            IDbConnection defaultConn = DefaultConnection;

            //ADO.NET数据库连接字符串
            db.Connection.ConnectionString = DefaultConnectionString;

            return(SqlQueryForDynamicOtherDB(db, sql, defaultConn, parameters));
        }
Esempio n. 8
0
        public void GetDBConnection(ValidationContext validationContext)
        {
            //var db = validationContext.ObjectInstance
            //Utils.ObjectJsonDumper.Dump(, 1);

            Console.WriteLine("getting DBContext for type: " + DBContextServiceType.ToString());

            //var ctx = (System.Data.Entity.DbContext)validationContext.GetService(DBContextServiceType);
            var ctx = DbContextGetter();

            Console.WriteLine("DBContext is null? " + (ctx == null));

            m_database = ctx.Database;
        }
Esempio n. 9
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var builder = modelBuilder.Entity <User>();

            builder.ToTable(nameof(User));
            builder.HasKey(p => p.Id);
            var model = modelBuilder.Build(Database.Connection);
            var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists <EntityContext>(modelBuilder);

            DataBase.SetInitializer(sqliteConnectionInitializer);
            //sqliteConnectionInitializer.InitializeDatabase(this);
            //IDatabaseCreator sqliteDatabaseCreator = new SqliteDatabaseCreator();
            //sqliteDatabaseCreator.Create(Database, model);
        }
        /// <summary>
        /// 基于当前 <paramref name="database"/> 获取与其相同数据库环境的 <see cref="NDF.Data.Common.Database"/> 实例对象。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <returns>与 <paramref name="database"/> 相同数据库环境的 <see cref="NDF.Data.Common.Database"/> 实例对象。</returns>
        public static NDF.Data.Common.Database GetGeneralDatabase(this System.Data.Entity.Database database)
        {
            string connectionString = GetConnectionString(database);

            lock (_databaseCache)
            {
                NDF.Data.Common.Database generalDatabase = null;
                if (!_databaseCache.Value.TryGetValue(connectionString, out generalDatabase))
                {
                    string providerName = GetProviderName(database);
                    generalDatabase = DatabaseFactories.GetFactory(providerName).CreateDatabase(connectionString);
                    _databaseCache.Value.Add(connectionString, generalDatabase);
                }
                return(generalDatabase);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a transaction and exectures the passed code then commits or rolls back automatically
        /// </summary>
        /// <param name="db"></param>
        /// <param name="cb">The code to execute</param>
        public static async Task Transaction(this System.Data.Entity.Database db, Func <Task> cb)
        {
            using (var tx = db.BeginTransaction())
            {
                try
                {
                    await cb();

                    tx.Commit();
                }
                catch (Exception)
                {
                    tx.Rollback();
                    throw;
                }
            }
        }
        public static dynamic SqlFunctionForDynamic(this System.Data.Entity.Database db,
                                                    string sql,
                                                    params object[] parameters)
        {
            IDbConnection conn = DefaultConnection;

            //ADO.NET数据库连接字符串
            conn.ConnectionString = DefaultConnectionString;

            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            IDbCommand cmd = conn.CreateCommand();

            cmd.CommandText = sql;
            cmd.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
            {
                foreach (var item in parameters)
                {
                    cmd.Parameters.Add(item);
                }
            }
            //1、DataReader查询数据
            using (IDataReader dataReader = cmd.ExecuteReader())
            {
                if (!dataReader.Read())
                {
                    return(null);
                }
                //2、DataReader转换Json
                string jsonstr = Common.JsonConverter.ToJson(dataReader);
                dataReader.Close();
                dataReader.Dispose();
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
                //3、Json转换动态类
                dynamic dyna = Common.JsonConverter.ConvertJson(jsonstr);
                return(dyna);
            }
        }
        /// <summary>
        /// Wrapper function of Database.SqlQuery<T>.
        /// T can be any view, not necessary predefined model class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="self"></param>
        /// <param name="sp"></param>
        /// <returns></returns>
        public static IEnumerable <T> SqlQuery <T>(this System.Data.Entity.Database self, IStoredProcedureBase sp)
        {
            if (self == null)
            {
                throw new ArgumentNullException("self");
            }
            if (sp == null)
            {
                throw new ArgumentException("IStoredProcedure sp");
            }
            var arguments = PrepareArguments(sp);

            try
            {
                return(self.SqlQuery <T>(arguments.Item1, arguments.Item2));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Esempio n. 14
0
 public static ICoreQueryable <T> QueryData <T>(this System.Data.Entity.Database database)
 {
     return(new CoreQueryable <T>(database));
 }
Esempio n. 15
0
 /// <summary>
 /// 获取数据库连接;
 /// </summary>
 /// <param name="databaseFacade"></param>
 /// <returns></returns>
 public static DbConnection GetDbConnection(this DatabaseFacade databaseFacade)
 {
     return(databaseFacade.Connection);
 }
Esempio n. 16
0
 /// <summary>
 /// 秒数;
 /// </summary>
 /// <param name="databaseFacade"></param>
 /// <param name="commandTimeout">秒为单位;</param>
 public static void SetCommandTimeout(this DatabaseFacade databaseFacade, int commandTimeout)
 {
     databaseFacade.CommandTimeout = commandTimeout;
 }
        private static IEnumerable SqlQueryForDynamicOtherDB(this System.Data.Entity.Database db, string sql, IDbConnection conn, params object[] parameters)
        {
            conn.ConnectionString = db.Connection.ConnectionString;

            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            IDbCommand cmd = conn.CreateCommand();

            cmd.CommandText = sql;
            if (parameters != null)
            {
                foreach (var item in parameters)
                {
                    cmd.Parameters.Add(item);
                }
            }

            using (IDataReader dataReader = cmd.ExecuteReader())
            {
                if (!dataReader.Read())
                {
                    return(null); //无结果返回Null
                }

                #region 构建动态字段

                TypeBuilder builder = DatabaseExtensions.CreateTypeBuilder(
                    "EF_DynamicModelAssembly",
                    "DynamicModule",
                    "DynamicType");

                int fieldCount = dataReader.FieldCount;
                for (int i = 0; i < fieldCount; i++)
                {
                    Type t = dataReader.GetFieldType(i);
                    switch (t.Name.ToLower())
                    {
                    case "decimal":
                        t = typeof(Decimal?);
                        break;

                    case "double":
                        t = typeof(Double?);
                        break;

                    case "datetime":
                        t = typeof(DateTime?);
                        break;

                    case "single":
                        t = typeof(float?);
                        break;

                    case "int16":
                        t = typeof(int?);
                        break;

                    case "int32":
                        t = typeof(int?);
                        break;

                    case "int64":
                        t = typeof(int?);
                        break;

                    default:
                        break;
                    }
                    DatabaseExtensions.CreateAutoImplementedProperty(
                        builder,
                        dataReader.GetName(i),
                        t);
                }

                #endregion

                cmd.Parameters.Clear();
                dataReader.Close();
                dataReader.Dispose();
                cmd.Dispose();
                conn.Close();
                conn.Dispose();

                Type returnType = builder.CreateType();

                if (parameters != null)
                {
                    return(db.SqlQuery(returnType, sql, parameters));
                }
                else
                {
                    return(db.SqlQuery(returnType, sql));
                }
            }
        }
 /// <summary>
 /// 检查数据库是否与当前 Code First 模型兼容。
 /// <para>该方法等效于调用方法时 <see cref="System.Data.Entity.Database.CompatibleWithModel(Boolean)"/> 传入参数 false。</para>
 /// </summary>
 /// <param name="_this">表示 <see cref="System.Data.Entity.DbContext"/> 实体上下文对象中引用的 数据库实例。</param>
 /// <returns>如果该数据库实例与当前 Code First 模型兼容,则返回 true,否则返回 false。</returns>
 /// <remarks>
 /// 该方法内部调用 <see cref="System.Data.Entity.Database"/> 对象的 CompatibleWithModel(false) 进行判断。
 /// </remarks>
 public static bool CompatibleWithModel(this System.Data.Entity.Database _this)
 {
     return(_this.CompatibleWithModel(false));
 }
Esempio n. 19
0
 public Database(System.Data.Entity.Database database)
 {
     _database = database;
 }
        /// <summary>
        /// 解析 SQL 脚本中的参数名称列表并返回。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <param name="sqlScript">待解析的 SQL 脚本。</param>
        /// <returns>返回 <paramref name="sqlScript"/> 中定义的所有脚本参数名称所构成的一个数组。</returns>
        public static string[] GetParameterNames(this System.Data.Entity.Database database, string sqlScript)
        {
            DbScriptParameterParser parser = GetDbScriptParameterParser(database);

            return(parser.GetParameterNames(sqlScript));
        }
        /// <summary>
        /// 获取表示与当前 <see cref="DbProviderFactory"/> 关联的 <see cref="DbCommand"/> 查询参数名称前缀字符。
        /// </summary>
        /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
        /// <returns>表示与当前 <see cref="DbProviderFactory"/> 关联的 <see cref="DbCommand"/> 查询参数名称前缀字符。</returns>
        public static string GetParameterToken(this System.Data.Entity.Database database)
        {
            DbScriptParameterParser parser = GetDbScriptParameterParser(database);

            return(parser.ParameterToken);
        }
 /// <summary>
 /// 获取该数据库访问对象的数据库连接字符串值。
 /// </summary>
 /// <param name="database">表示一个 <see cref="System.Data.Entity.Database"/> 对象。</param>
 /// <returns>该数据库访问对象的数据库连接字符串值。</returns>
 public static string GetConnectionString(this System.Data.Entity.Database database)
 {
     return(database.Connection.ConnectionString);
 }
 Setup()
 {
     EFDatabase.SetInitializer <DemoDbContext>(
         new DropCreateDatabaseIfModelChanges <DemoDbContext>());
 }
Esempio n. 24
0
 static TestHelper()
 {
     Database.SetInitializer(new MigrateDatabaseToLatestVersion <ScribeSqlDatabase, Configuration>(true));
 }
Esempio n. 25
0
 public static ICoreQueryable <object> QueryData(this System.Data.Entity.Database database, string schemaName)
 {
     return(new CoreQueryable <object>(database));
 }
Esempio n. 26
0
 public ApplicationDbContext() : base("name=SqlServer")
 {
     Database.SetInitializer(new TodosInitializer());
     //Database.Initialize(true);
 }
Esempio n. 27
0
 public CoreQueryable(System.Data.Entity.Database database)
 {
     _database = database;
     Query     = new SqlLam <T>();
     Query._builder.QueryByFieldNotNull(typeof(T).Name, "Id");
 }
Esempio n. 28
0
 public BgDataContext(string connectionString)
     : base(_sqlConnection = new SQLiteConnection(_connectionString = connectionString), true)
 {
     _sqlConnection.Open();
     Entity.SetInitializer <BgDataContext>(null);
 }
Esempio n. 29
0
 public AppDbContext()
 {
     Database.SetInitializer <AppDbContext>(null);
     InstanceId = Guid.NewGuid();
 }