public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") //.UseSyncStructureToUpper(true) .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), (cmd, log) => Trace.WriteLine(log) ) .Build(); Fsql2 = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") .UseLogger(loggerFactory.CreateLogger <IFreeSql>()) .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), (cmd, log) => Trace.WriteLine(log) ) .Build <long>(); }
private IFreeSql CreateDb(FreeSql.DataType dbType, DbInfo currentDbOption) { var master = currentDbOption.ConnectionStrings?.FirstOrDefault(e => e.UseType == DbUseType.Master); if (master == null) { throw new ArgumentNullException($"请设置租户 {Tenant.Code} 的主库连接字符串"); } var slaveConnectionStrings = currentDbOption.ConnectionStrings?.Where(e => e.UseType == DbUseType.Slave).Select(e => e.ConnectionString).ToArray(); var freeSqlBuilder = new FreeSql.FreeSqlBuilder() .UseConnectionString(dbType, master.ConnectionString); if (slaveConnectionStrings?.Length > 0) { freeSqlBuilder = freeSqlBuilder.UseSlave(slaveConnectionStrings); } if (_env.IsDevelopment()) { freeSqlBuilder = freeSqlBuilder.UseAutoSyncStructure(true); //自动同步实体结构【开发环境必备】 } var fsql = freeSqlBuilder.Build(); fsql.Aop.ConfigEntityProperty += ConfigEntityProperty; fsql.Aop.CurdBefore += CurdBefore; fsql.Aop.AuditValue += AuditValue; //fsql.Aop.SyncStructureAfter += SyncStructureAfter; DataFilterAsync(fsql); return(fsql); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var dataCenterId = Configuration.GetValue <long>("DataCenterId"); var serverId = Configuration.GetValue <long>("ServerId"); services.AddSingleton <IdBuilder>(p => new IdBuilder(dataCenterId, serverId)); services.AddSingleton <IFreeSql>((provider) => { var connectString = Configuration.GetConnectionString("OrderServiceDB"); var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connectString).Build(); return(fsql); }); var redisConnectString = Configuration.GetConnectionString("WisderMicroServiceRedis"); services.AddDistributedRedisCache(redisConnectString); services.AddScoped <UnitOfWorkManager>(); services.AddScoped <IOrderRepository, OrderRepository>(); services.AddScoped <IOrderService, OrderServiceImpl>(); services.AddConsul(); services.AddControllers(); }
/// <summary> /// 添加FreeSqlGen相关 /// 模板地址默认:DefaultTemplatePath = "RazorTemplate" /// sqlite持久化默认地址 SqliteDbConnectionString="Data Source=fsbuilder.db;Version=3" /// </summary> /// <param name="services"></param> /// <param name="setupAction">生成器模板配置项</param> public static void AddFreeSqlBuilder(this IServiceCollection services, Action <FreeSqlBuilderOption> setupAction = null) { var options = new FreeSqlBuilderOption(); setupAction?.Invoke(options); if (string.IsNullOrWhiteSpace(options.DbSet.ConnectionString)) { throw new Exception("ConnectionString必须填写"); } services.AddSingleton(options); //配置导入 services.AddMvc(opt => opt.EnableEndpointRouting = false) .AddNewtonsoftJson(option => option.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore) //防止递归导致json输出不正确 .AddRazorRuntimeCompilation(); //MVC动态编译 ; services.AddFreeSqlBuilderCore(); services.AddSingleton <HtmlEncoder>(NullHtmlEncoder.Default); //HTML中文编码处理 services.AddSingleton <FileProviderHelper>(); //文件相关处理 services.AddMemoryCache(); services.AddSingleton <IFreeSql <FsBuilder> >(x => { var builder = new FreeSql.FreeSqlBuilder() .UseConnectionString(dataType: options.DbSet.DbType, options.DbSet.ConnectionString) .UseAutoSyncStructure(true) .Build <FsBuilder>(); builder.Aop.CommandAfter += (s, e) => Aop_CommandAfter(s, e, x.GetService <ILogger <IFreeSql> >()); return(builder); }); //持久化 services.AddScoped <IUnitOfWork>(x => x.GetService <IFreeSql <FsBuilder> >().CreateUnitOfWork()); services.AddScoped <ReflectionHelper>(); //反射助手 services.AddScoped <BuildTask>(); //核心任务 services.AddSingleton <RazorTemplateEngine>(); //Razor模板引擎 services.AddTransient <RazorViewToStringRender>(); //Razor渲染字符串 services.AddScoped <DefaultDataInit>(); }
protected void TestDb() { var systemDb = TenantItem.DbOptions.Where(x => x.Key.ToLower() == "system").FirstOrDefault(); if (systemDb == null) { _ = MessageBox.AlertAsync("找不到System数据库配置"); return; } try { var dbType = (FreeSql.DataType)Enum.Parse(typeof(FreeSql.DataType), systemDb.DbType); var connStr = systemDb.ConnectionStrings.Where(x => x.UseType == DbUseType.Master).First().ConnectionString; IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(dbType, connStr) .Build(); // 这儿验证 连接是否成功 //var a = fsql.DbFirst.GetDatabases(); //Fsql.Ado.MasterPool.Get().Value DbConnection dbConnection = fsql.Ado.MasterPool.Get().Value; fsql.Dispose(); _ = MessageBox.AlertAsync("连接成功"); } catch (Exception ex) { _ = MessageBox.AlertAsync(ex.Message); } finally{ } }
private static IFreeSql SelectDBType(DataType enum_dbtype) { var dbtype = enum_dbtype.ToString(); if (!ConnectionPool.ContainsKey(dbtype)) { var freesql = new FreeSql.FreeSqlBuilder() .UseConnectionString(enum_dbtype, AppConfig.ConnectionString()) .UseAutoSyncStructure(false) //是否根据实体修改数据库, Code-First .UseMonitorCommand( cmd => { Console.WriteLine("============================================"); Console.WriteLine(""); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); Console.WriteLine(""); Console.WriteLine(cmd.CommandText); Console.WriteLine("============================================"); } ) .UseLazyLoading(true) .Build(); ConnectionPool.Add(dbtype, freesql); } return(ConnectionPool[dbtype]); }
private static IFreeSql SelectDBType(DataType enum_dbtype) { var dbtype = enum_dbtype.ToString(); if (!ConnectionPool.ContainsKey(dbtype)) { var freesql = new FreeSql.FreeSqlBuilder() .UseConnectionString(enum_dbtype, getConnectionString(dbtype)) .UseAutoSyncStructure(true) .UseMonitorCommand( cmd => { Trace.WriteLine(cmd.CommandText); }, //监听SQL命令对象,在执行前 (cmd, traceLog) => { Console.WriteLine(traceLog); }) //监听SQL命令对象,在执行后 .UseLazyLoading(true) .Build(); freesql.Aop.ConfigEntityProperty += Aop_ConfigEntityProperty; ConnectionPool.Add(dbtype, freesql); } return(ConnectionPool[dbtype]); }
public BaseStorage(BaseStorageOptions options) { _options = options; _deferFlushCollection = new AsyncCallbackDeferFlushCollection <RequestBag>(AddRequestInfoAsync, _options.DeferThreshold, _options.DeferSecond); freeSql = new FreeSql.FreeSqlBuilder().UseConnectionString(_options.DataType, _options.ConnectionString).UseNoneCommandParameter(true).Build(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region Swagger 配置 // 将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "订单采集小程序 API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); #endregion // 添加 HttpContextAccessor,这样就可以注入控制器 使用 HttpContext // HttpContext 可以获取当前认证通过的用户信息 services.AddHttpContextAccessor(); //钉钉客户端 SDK 配置 var appkey = Configuration.GetSection("DingTalk:Appkey").Value; var appsecret = Configuration.GetSection("DingTalk:Appsecret").Value; services.AddDingTalk(appkey, appsecret); #region JWT 认证配置 // 添加认证方式 JwtBearerDefaults ,配置 JWT 认证项 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = "Zilor", // 待验证发放者,与 TokenController 里的要一致 ValidAudience = "Zilor", // 待验证接受者,与 TokenController 里的要一致 // 签名加密 key,即 JWT 密钥,与 TokenController 里的要一致 IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["JwtSecret"])), ValidateIssuer = true, // 验证 发放者 ValidateAudience = true, // 验证 接受者 ValidateLifetime = true, // 验证 到期时间 ValidateIssuerSigningKey = true // 验证 签名 }; }); #endregion // FreeSql var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, Configuration.GetConnectionString("DefaultConnection")) .Build(); services.AddSingleton <IFreeSql>(fsql); }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") .UseLogger(loggerFactory.CreateLogger <IFreeSql>()) .UseAutoSyncStructure(true) .Build(); }
public Startup(IConfiguration configuration) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\test_trans.db") .UseAutoSyncStructure(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) .UseNoneCommandParameter(true) .Build(); }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document.db;Pooling=true;Max Pool Size=10") .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText + "\r\n")) .Build(); }
/// <summary> /// 获取FreeSQL /// </summary> /// <param name="connectionString">连接字符串</param> private static IFreeSql GetFreeSql(string connectionString) { var fsql = new FreeSql.FreeSqlBuilder() .UseAutoSyncStructure(false) .UseNoneCommandParameter(true) .UseConnectionString(DataType.MySql, connectionString) //.UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText)) .Build(); return(fsql); }
protected override void OnConfiguring(DbContextOptionsBuilder builder) { var _freeSql = new FreeSql.FreeSqlBuilder() .UseConnectionString(DataType.SqlServer, FreeSqlTests.ConnectionString) .UseAutoSyncStructure(false) .Build(); _freeSql.CodeFirst.ConfigEntity <Int32Sample>(t => t.Name("Int32Samples")); builder.UseFreeSql(_freeSql); }
static void Main(string[] args) { IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.SqlServer, "Server=localhost;Database=test;Trusted_Connection=True;MultipleActiveResultSets=true") .UseAutoSyncStructure(true) //自动同步实体结构到数据库 .Build(); //请务必定义成 Singleton 单例模式 var sql = fsql.CodeFirst.GetComparisonDDLStatements <TestModel>(); fsql.CodeFirst.SyncStructure <TestModel>(); }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; var mySqlConnstr = configuration.GetConnectionString("MasterMysql"); MasterManagerDB = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, mySqlConnstr) .UseLogger(loggerFactory.CreateLogger <IFreeSql>()) .UseAutoSyncStructure(true) .UseLazyLoading(true) .Build <MasterDb>(); MasterManagerDB.CodeFirst.SyncStructure(typeof(Users)); }
public Startup(IConfiguration configuration) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\test_trans.db") .UseAutoSyncStructure(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) .UseNoneCommandParameter(true) .Build(); Fsql.Aop.TraceBefore += (_, e) => Trace.WriteLine($"----TraceBefore---{e.Identifier} {e.Operation}"); Fsql.Aop.TraceAfter += (_, e) => Trace.WriteLine($"----TraceAfter---{e.Identifier} {e.Operation} {e.Remark} {e.Exception?.Message} {e.ElapsedMilliseconds}ms\r\n"); }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") //.UseConnectionString(DataType.MySql, "Data Source=192.168.164.10;Port=33061;User ID=root;Password=123456;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=5") //.UseSlave("Data Source=192.168.164.10;Port=33062;User ID=root;Password=123456;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=5") //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") //.UseSyncStructureToUpper(true) .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), (cmd, log) => Trace.WriteLine(log) ) .Build(); Fsql.Aop.SyncStructureBefore += (s, e) => { Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName))); }; Fsql.Aop.SyncStructureAfter += (s, e) => { Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql); }; Fsql.Aop.CurdBefore += (s, e) => { Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql); }; Fsql.Aop.CurdAfter += (s, e) => { Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql); }; Fsql2 = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), (cmd, log) => Trace.WriteLine(log) ) .Build <long>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddConsul(); string connectString = "", redisConnectString = ""; //var connectString = Configuration.GetConnectionString("IdentityServerDB"); //var redisConnectString = Configuration.GetConnectionString("WisderMicroServiceRedis"); #region 从配置中心获取配置参数 var consulAddress = Environment.GetEnvironmentVariable("WisderRegistryAddress"); using (Consul.ConsulClient consulClient = new Consul.ConsulClient(config => { config.Address = new Uri(consulAddress); })) { connectString = Encoding.UTF8.GetString(consulClient.KV.Get("UserServiceDB").Result.Response.Value); redisConnectString = Encoding.UTF8.GetString(consulClient.KV.Get("WisderMicroServiceRedis").Result.Response.Value); } #endregion var dataCenterId = Configuration.GetValue <long>("DataCenterId"); var serverId = Configuration.GetValue <long>("ServerId"); services.AddSingleton <IdBuilder>(p => new IdBuilder(dataCenterId, serverId)); services.AddSingleton <IFreeSql>((provider) => { var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connectString).Build(); return(fsql); }); services.AddDistributedRedisCache(redisConnectString); services.AddScoped <UnitOfWorkManager>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IUserService, UserServiceImpl>(); services.AddControllers(option => { option.Filters.Add <BizExceptionFilter>(); }).AddNewtonsoftJson(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //不使用驼峰样式的key options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); }
public Startup(IConfiguration configuration) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"DataSource=:memory:;Pooling=true;Max Pool Size=10") .UseAutoSyncStructure(true) .Build(); InitData(); Fsql.Aop.CurdAfter += (s, e) => { if (e.ElapsedMilliseconds > 200) { //记录日志 //发送短信给负责人 } }; }
public override void TestDataConnection() { var connString = textBoxX2.Text; try { var dataType = GetDataType(); var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(dataType, connString).Build(); fsql.DbFirst.GetDatabases(); MessageBoxEx.Show("数据库连接成功", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { TaskDialog.Show("错误提示", eTaskDialogIcon.BlueStop, "数据库连接失败", $" 原因:{e.Message}\n 连接串:{connString}\n", eTaskDialogButton.Ok); } }
private static IFreeSql SelectDBType(DataType enum_dbtype) { var dbtype = enum_dbtype.ToString(); if (!ConnectionPool.ContainsKey(dbtype)) { var freesql = new FreeSql.FreeSqlBuilder() .UseConnectionString(enum_dbtype, getConnectionString(dbtype)) .UseAutoSyncStructure(true) .UseMonitorCommand( cmd => { Trace.WriteLine(cmd.CommandText); }, //监听SQL命令对象,在执行前 (cmd, traceLog) => { Console.WriteLine(traceLog); }) //监听SQL命令对象,在执行后 .UseLazyLoading(true) .Build(); freesql.Aop.ConfigEntityProperty += (s, e) => { //默认设置主键 if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any()) { e.ModifyResult.IsPrimary = true; } //设置maxlength if (e.Property.PropertyType == typeof(string)) { var strLen = e.Property.GetCustomAttribute <System.ComponentModel.DataAnnotations.MaxLengthAttribute>(); if (strLen != null) { e.ModifyResult.DbType = freesql.CodeFirst.GetDbInfo(e.Property.PropertyType)?.dbtype + "(" + strLen.Length + ")"; } } }; ConnectionPool.Add(dbtype, freesql); } return(ConnectionPool[dbtype]); }
public Startup(IConfiguration configuration) { Console.WriteLine(configuration["connectionString"].ToString()); var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, configuration["connectionString"].ToString()) .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .Build(); fsql.Aop.ConfigEntityProperty += new EventHandler <FreeSql.Aop.ConfigEntityPropertyEventArgs>((_, e) => { if (fsql.Ado.DataType == FreeSql.DataType.MySql || fsql.Ado.DataType == FreeSql.DataType.OdbcMySql) { return; } if (e.Property.PropertyType.IsEnum == false) { return; } e.ModifyResult.MapType = typeof(string); }); fsql.Aop.CurdBefore += new EventHandler <FreeSql.Aop.CurdBeforeEventArgs>((_, e) => Trace.WriteLine(e.Sql)); BaseEntity.Initialization(fsql, null); Fsql = fsql; Configuration = configuration; Redis = new RedisClient(configuration["redis"]); Redis.Serialize = obj => JsonConvert.SerializeObject(obj); Redis.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type); DDZ.GamePlay.OnSaveData = (id, d) => Redis.HSet($"DDZrdb", id, d); DDZ.GamePlay.OnGetData = id => Redis.HGet <GameInfo>("DDZrdb", id); Newtonsoft.Json.JsonConvert.DefaultSettings = () => { var st = new Newtonsoft.Json.JsonSerializerSettings(); st.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); st.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; st.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.RoundtripKind; return(st); }; }
public static void InitialiseSQLite() { if (initialised) { return; } AsyncLocal <IUnitOfWork> asyncUow = new AsyncLocal <IUnitOfWork>(); Directory.CreateDirectory("../../../Data"); var fsql = new FreeSql.FreeSqlBuilder() .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=../../../Data/FreeSQL.sqlite;max pool size=5") .UseMonitorCommand(null, (umcmd, log) => Console.WriteLine(umcmd.Connection.ConnectionString + ":" + umcmd.CommandText)) .UseLazyLoading(true) .UseGenerateCommandParameterWithLambda(true) .Build(); BaseEntity.Initialization(fsql, () => asyncUow.Value); initialised = true; }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) .Build(); var sysu = new Sys1User { }; Fsql.Insert <Sys1User>().AppendData(sysu).ExecuteAffrows(); Fsql.Insert <Sys1UserLogOn>().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows(); var a = Fsql.Select <Sys1UserLogOn>().ToList(); var b = Fsql.Select <Sys1UserLogOn>().Any(); }
public async Task <IResponseEntity> CreateDb(DbCreateItem req) { try { var dbType = (FreeSql.DataType)Enum.Parse(typeof(FreeSql.DataType), req.DbType); var connStr = req.ConnectionString; IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(dbType, connStr) .Build(); Console.WriteLine("\r\n开始建库"); await fsql.Ado.ExecuteNonQueryAsync(req.CreateDbCommand); fsql.Dispose(); Console.WriteLine("建库完成\r\n"); return(ResponseEntity.Ok("创建成功")); } catch (Exception ex) { Console.WriteLine($"建库失败.\n{ex.Message}\r\n"); return(ResponseEntity.Error(ex.Message)); } }
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") //.UseConnectionString(DataType.MySql, "Data Source=192.168.164.10;Port=33061;User ID=root;Password=123456;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=5") //.UseSlave("Data Source=192.168.164.10;Port=33062;User ID=root;Password=123456;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=5") //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") //.UseSyncStructureToUpper(true) .UseAutoSyncStructure(true) .UseLazyLoading(true) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => { }, (cmd, log) => Trace.WriteLine(log)) .Build(); Fsql.Aop.CurdAfter += (s, e) => { Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql); CurdAfterLog.Current.Value?.Sb.AppendLine($"{Thread.CurrentThread.ManagedThreadId}: {e.EntityType.FullName} {e.ElapsedMilliseconds}ms, {e.Sql}"); }; }
public IResponseEntity TestDbConnect(DbConnectItem req) { try { var dbType = (FreeSql.DataType)Enum.Parse(typeof(FreeSql.DataType), req.DbType); var connStr = req.ConnectionString; IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(dbType, connStr) .Build(); // 这儿验证 连接是否成功 //var a = fsql.DbFirst.GetDatabases(); //Fsql.Ado.MasterPool.Get().Value DbConnection dbConnection = fsql.Ado.MasterPool.Get().Value; fsql.Dispose(); return(ResponseEntity.Ok("连接成功")); } catch (Exception ex) { return(ResponseEntity.Error(ex.Message)); } }
static void Main(string[] args) { #region 初始化 IFreeSql var fsql = new FreeSql.FreeSqlBuilder() .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test.db;max pool size=5") //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3") .UseLazyLoading(true) .Build(); BaseEntity.Initialization(fsql); #endregion var us = User1.Select.Limit(10).ToList(); new Products { title = "product-1" }.Save(); new Products { title = "product-2" }.Save(); new Products { title = "product-3" }.Save(); new Products { title = "product-4" }.Save(); new Products { title = "product-5" }.Save(); var items1 = Products.Select.Limit(10).OrderByDescending(a => a.CreateTime).ToList(); var items2 = fsql.Select <Products>().Limit(10).OrderByDescending(a => a.CreateTime).ToList(); BaseEntity.Orm.UseJsonMap(); new S_SysConfig <TestConfig> { Name = "testkey11", Config = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey22", Config = new TestConfig { clicks = 22, title = "testtitle22" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey33", Config = new TestConfig { clicks = 33, title = "testtitle33" } }.Save(); var testconfigs11 = S_SysConfig <TestConfig> .Select.ToList(); var repo = BaseEntity.Orm.Select <TestConfig>().Limit(10).ToList(); Task.Run(async() => { using (var uow = BaseEntity.Begin()) { var id = (await new User1().SaveAsync()).Id; uow.Commit(); } var ug1 = new UserGroup(); ug1.GroupName = "分组一"; await ug1.InsertAsync(); var ug2 = new UserGroup(); ug2.GroupName = "分组二"; await ug2.InsertAsync(); var u1 = new User1(); u1.GroupId = ug1.Id; await u1.SaveAsync(); await u1.DeleteAsync(); await u1.RestoreAsync(); u1.Nickname = "x1"; await u1.UpdateAsync(); var u11 = await User1.FindAsync(u1.Id); u11.Description = "备注"; await u11.SaveAsync(); await u11.DeleteAsync(); var slslsl = Newtonsoft.Json.JsonConvert.SerializeObject(u1); var u11null = User1.Find(u1.Id); var u11s = User1.Where(a => a.Group.Id == ug1.Id).Limit(10).ToList(); var u11s2 = User1.Select.LeftJoin <UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList(); var ug1s = UserGroup.Select .IncludeMany(a => a.User1s) .Limit(10).ToList(); var ug1s2 = UserGroup.Select.Where(a => a.User1s.AsSelect().Any(b => b.Nickname == "x1")).Limit(10).ToList(); var r1 = new Role(); r1.Id = "管理员"; await r1.SaveAsync(); var r2 = new Role(); r2.Id = "超级会员"; await r2.SaveAsync(); var ru1 = new RoleUser1(); ru1.User1Id = u1.Id; ru1.RoleId = r1.Id; await ru1.SaveAsync(); ru1.RoleId = r2.Id; await ru1.SaveAsync(); var u1roles = await User1.Select.IncludeMany(a => a.Roles).ToListAsync(); var u1roles2 = await User1.Select.Where(a => a.Roles.AsSelect().Any(b => b.Id == "xx")).ToListAsync(); }).Wait(); Console.WriteLine("按任意键结束。。。"); Console.ReadKey(); }
static void Main(string[] args) { #region 初始化 IFreeSql var fsql = new FreeSql.FreeSqlBuilder() //.UseAutoSyncStructure(true) .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test1.db;max pool size=5") //.UseSlave("data source=test1.db", "data source=test2.db", "data source=test3.db", "data source=test4.db") //.UseSlaveWeight(10, 1, 1, 5) //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3") .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=2") .UseNameConvert(FreeSql.Internal.NameConvertType.ToLower) //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=2") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) //.UseConnectionString(FreeSql.DataType.OdbcMySql, "Driver={MySQL ODBC 8.0 Unicode Driver};Server=127.0.0.1;Persist Security Info=False;Trusted_Connection=Yes;UID=root;PWD=root;DATABASE=cccddd_odbc;Charset=utf8;SslMode=none;Max pool size=2") //.UseConnectionString(FreeSql.DataType.OdbcSqlServer, "Driver={SQL Server};Server=.;Persist Security Info=False;Trusted_Connection=Yes;Integrated Security=True;DATABASE=freesqlTest_odbc;Pooling=true;Max pool size=3") //.UseConnectionString(FreeSql.DataType.OdbcPostgreSQL, "Driver={PostgreSQL Unicode(x64)};Server=192.168.164.10;Port=5432;UID=postgres;PWD=123456;Database=tedb_odbc;Pooling=true;Maximum Pool Size=2") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToLower) //.UseConnectionString(FreeSql.DataType.OdbcOracle, "Driver={Oracle in XE};Server=//127.0.0.1:1521/XE;Persist Security Info=False;Trusted_Connection=Yes;UID=odbc1;PWD=123456") //.UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) //.UseConnectionString(FreeSql.DataType.OdbcDameng, "Driver={DM8 ODBC DRIVER};Server=127.0.0.1:5236;Persist Security Info=False;Trusted_Connection=Yes;UID=USER1;PWD=123456789") .UseMonitorCommand(null, (umcmd, log) => Console.WriteLine(umcmd.Connection.ConnectionString + ":" + umcmd.CommandText)) .UseLazyLoading(true) .UseGenerateCommandParameterWithLambda(true) .Build(); BaseEntity.Initialization(fsql, () => _asyncUow.Value); #endregion fsql.Aop.ParseExpression += (_, e) => { //解析 POCO Jsonb a.Customer.Name if (e.Expression is MemberExpression memExp) { var parentMemExps = new Stack <MemberExpression>(); parentMemExps.Push(memExp); while (true) { switch (memExp.Expression.NodeType) { case ExpressionType.MemberAccess: memExp = memExp.Expression as MemberExpression; if (memExp == null) { return; } parentMemExps.Push(memExp); break; case ExpressionType.Parameter: var tb = fsql.CodeFirst.GetTableByEntity(memExp.Expression.Type); if (tb == null) { return; } if (tb.ColumnsByCs.TryGetValue(parentMemExps.Pop().Member.Name, out var trycol) == false) { return; } if (new[] { typeof(JToken), typeof(JObject), typeof(JArray) }.Contains(trycol.Attribute.MapType.NullableTypeOrThis()) == false) { return; } var tmpcol = tb.ColumnsByPosition.OrderBy(a => a.Attribute.Name.Length).First(); var result = e.FreeParse(Expression.MakeMemberAccess(memExp.Expression, tb.Properties[tmpcol.CsName])); result = result.Replace(tmpcol.Attribute.Name, trycol.Attribute.Name); while (parentMemExps.Any()) { memExp = parentMemExps.Pop(); result = $"{result}->>'{memExp.Member.Name}'"; } e.Result = result; return; } } } }; var methodJsonConvertDeserializeObject = typeof(JsonConvert).GetMethod("DeserializeObject", new[] { typeof(string), typeof(Type) }); var methodJsonConvertSerializeObject = typeof(JsonConvert).GetMethod("SerializeObject", new[] { typeof(object), typeof(JsonSerializerSettings) }); var jsonConvertSettings = JsonConvert.DefaultSettings?.Invoke() ?? new JsonSerializerSettings(); FreeSql.Internal.Utils.dicExecuteArrayRowReadClassOrTuple[typeof(Customer)] = true; FreeSql.Internal.Utils.GetDataReaderValueBlockExpressionObjectToStringIfThenElse.Add((LabelTarget returnTarget, Expression valueExp, Expression elseExp, Type type) => { return(Expression.IfThenElse( Expression.TypeIs(valueExp, typeof(Customer)), Expression.Return(returnTarget, Expression.Call(methodJsonConvertSerializeObject, Expression.Convert(valueExp, typeof(object)), Expression.Constant(jsonConvertSettings)), typeof(object)), elseExp)); }); FreeSql.Internal.Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, Type type) => { if (type == typeof(Customer)) { return(Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(methodJsonConvertDeserializeObject, Expression.Convert(valueExp, typeof(string)), Expression.Constant(type)), type))); } return(null); }); var seid = fsql.Insert(new SomeEntity { Customer = JsonConvert.DeserializeObject <Customer>(@"{ ""Age"": 25, ""Name"": ""Joe"", ""Orders"": [ { ""OrderPrice"": 9, ""ShippingAddress"": ""Some address 1"" }, { ""OrderPrice"": 23, ""ShippingAddress"": ""Some address 2"" } ] }") }).ExecuteIdentity(); var selist = fsql.Select <SomeEntity>().ToList(); var joes = fsql.Select <SomeEntity>() .Where(e => e.Customer.Name == "Joe") .ToSql(); var testitems = new[] { new AsTableLog { msg = "msg01", createtime = DateTime.Parse("2022-1-1 13:00:11") }, new AsTableLog { msg = "msg02", createtime = DateTime.Parse("2022-1-2 14:00:12") }, new AsTableLog { msg = "msg03", createtime = DateTime.Parse("2022-2-2 15:00:13") }, new AsTableLog { msg = "msg04", createtime = DateTime.Parse("2022-2-8 15:00:13") }, new AsTableLog { msg = "msg05", createtime = DateTime.Parse("2022-3-8 15:00:13") }, new AsTableLog { msg = "msg06", createtime = DateTime.Parse("2022-4-8 15:00:13") }, new AsTableLog { msg = "msg07", createtime = DateTime.Parse("2022-6-8 15:00:13") }, new AsTableLog { msg = "msg07", createtime = DateTime.Parse("2022-7-1") } }; var sqlatb = fsql.Insert(testitems).NoneParameter(); var sqlat = sqlatb.ToSql(); var sqlatr = sqlatb.ExecuteAffrows(); var sqlatc = fsql.Delete <AsTableLog>().Where(a => a.id == Guid.NewGuid() && a.createtime.Between(DateTime.Parse("2022-3-1"), DateTime.Parse("2022-5-1"))); var sqlatca = sqlatc.ToSql(); var sqlatcr = sqlatc.ExecuteAffrows(); var sqlatd1 = fsql.Update <AsTableLog>().SetSource(testitems[0]); var sqlatd101 = sqlatd1.ToSql(); var sqlatd102 = sqlatd1.ExecuteAffrows(); var sqlatd2 = fsql.Update <AsTableLog>().SetSource(testitems[5]); var sqlatd201 = sqlatd2.ToSql(); var sqlatd202 = sqlatd2.ExecuteAffrows(); var sqlatd3 = fsql.Update <AsTableLog>().SetSource(testitems); var sqlatd301 = sqlatd3.ToSql(); var sqlatd302 = sqlatd3.ExecuteAffrows(); var sqlatd4 = fsql.Update <AsTableLog>(Guid.NewGuid()).Set(a => a.msg == "newmsg"); var sqlatd401 = sqlatd4.ToSql(); var sqlatd402 = sqlatd4.ExecuteAffrows(); var sqlatd5 = fsql.Update <AsTableLog>(Guid.NewGuid()).Set(a => a.msg == "newmsg").Where(a => a.createtime.Between(DateTime.Parse("2022-3-1"), DateTime.Parse("2022-5-1"))); var sqlatd501 = sqlatd5.ToSql(); var sqlatd502 = sqlatd5.ExecuteAffrows(); var sqlatd6 = fsql.Update <AsTableLog>(Guid.NewGuid()).Set(a => a.msg == "newmsg").Where(a => a.createtime > DateTime.Parse("2022-3-1") && a.createtime < DateTime.Parse("2022-5-1")); var sqlatd601 = sqlatd6.ToSql(); var sqlatd602 = sqlatd6.ExecuteAffrows(); var sqlatd7 = fsql.Update <AsTableLog>(Guid.NewGuid()).Set(a => a.msg == "newmsg").Where(a => a.createtime > DateTime.Parse("2022-3-1")); var sqlatd701 = sqlatd7.ToSql(); var sqlatd702 = sqlatd7.ExecuteAffrows(); var sqlatd8 = fsql.Update <AsTableLog>(Guid.NewGuid()).Set(a => a.msg == "newmsg").Where(a => a.createtime < DateTime.Parse("2022-5-1")); var sqlatd801 = sqlatd8.ToSql(); var sqlatd802 = sqlatd8.ExecuteAffrows(); var sqls1 = fsql.Select <AsTableLog>(); var sqls101 = sqls1.ToSql(); var sqls102 = sqls1.ToList(); var sqls2 = fsql.Select <AsTableLog>().Where(a => a.createtime.Between(DateTime.Parse("2022-3-1"), DateTime.Parse("2022-5-1"))); var sqls201 = sqls2.ToSql(); var sqls202 = sqls2.ToList(); var sqls3 = fsql.Select <AsTableLog>().Where(a => a.createtime > DateTime.Parse("2022-3-1") && a.createtime < DateTime.Parse("2022-5-1")); var sqls301 = sqls3.ToSql(); var sqls302 = sqls3.ToList(); var sqls4 = fsql.Select <AsTableLog>().Where(a => a.createtime > DateTime.Parse("2022-3-1")); var sqls401 = sqls4.ToSql(); var sqls402 = sqls4.ToList(); var sqls5 = fsql.Select <AsTableLog>().Where(a => a.createtime < DateTime.Parse("2022-5-1")); var sqls501 = sqls5.ToSql(); var sqls502 = sqls5.ToList(); fsql.Aop.AuditValue += new EventHandler <FreeSql.Aop.AuditValueEventArgs>((_, e) => { }); Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("id", 1); dic.Add("name", "xxxx"); var diclist = new List <Dictionary <string, object> >(); diclist.Add(dic); diclist.Add(new Dictionary <string, object> { ["id"] = 2, ["name"] = "yyyy" }); var sqss = fsql.InsertDict(dic).AsTable("table1").ToSql(); var sqss2 = fsql.InsertDict(diclist).AsTable("table1").ToSql(); sqss = fsql.InsertDict(dic).AsTable("table1").NoneParameter(false).ToSql(); sqss2 = fsql.InsertDict(diclist).AsTable("table1").NoneParameter(false).ToSql(); var sqlupd1 = fsql.UpdateDict(dic).AsTable("table1").WherePrimary("id").ToSql(); var sqlupd2 = fsql.UpdateDict(diclist).AsTable("table1").WherePrimary("id").ToSql(); var sqlupd11 = fsql.UpdateDict(dic).AsTable("table1").WherePrimary("id").NoneParameter(false).ToSql(); var sqlupd22 = fsql.UpdateDict(diclist).AsTable("table1").WherePrimary("id").NoneParameter(false).ToSql(); var sqldel1 = fsql.DeleteDict(dic).AsTable("table1").ToSql(); var sqldel2 = fsql.DeleteDict(diclist).AsTable("table1").ToSql(); diclist[1]["title"] = "newtitle"; var sqldel3 = fsql.DeleteDict(diclist).AsTable("table1").ToSql(); diclist.Clear(); diclist.Add(new Dictionary <string, object> { ["id"] = 1 }); diclist.Add(new Dictionary <string, object> { ["id"] = 2 }); var sqldel4 = fsql.DeleteDict(diclist).AsTable("table1").ToSql(); for (var a = 0; a < 10000; a++) { fsql.Select <User1>().First(); } for (var a = 0; a < 1000; a++) { fsql.Transaction(() => { var tran = fsql.Ado.TransactionCurrentThread; tran.Rollback(); }); } fsql.UseJsonMap(); var bid1 = 10; var list1 = fsql.Select <A>() .Where(a => a.BId == bid1); var aid1 = 11; var select2 = fsql.Select <B>(); (select2 as Select0Provider)._params = (list1 as Select0Provider)._params; var list2 = select2 .Where(a => list1.ToList(B => B.BId).Contains(a.Id)) .Where(a => a.Id == aid1) .ToSql(); //fsql.Aop.CommandBefore += (s, e) => //{ // e.States["xxx"] = 111; //}; //fsql.Aop.CommandAfter += (s, e) => //{ // var xxx = e.States["xxx"]; //}; //fsql.Aop.TraceBefore += (s, e) => //{ // e.States["xxx"] = 222; //}; //fsql.Aop.TraceAfter += (s, e) => //{ // var xxx = e.States["xxx"]; //}; //fsql.Aop.SyncStructureBefore += (s, e) => //{ // e.States["xxx"] = 333; //}; //fsql.Aop.SyncStructureAfter += (s, e) => //{ // var xxx = e.States["xxx"]; //}; //fsql.Aop.CurdBefore += (s, e) => //{ // e.States["xxx"] = 444; //}; //fsql.Aop.CurdAfter += (s, e) => //{ // var xxx = e.States["xxx"]; //}; fsql.Insert(new tttorder("xx1", 1, 10)).ExecuteAffrows(); fsql.Insert(new tttorder("xx2", 2, 20)).ExecuteAffrows(); var tttorders = fsql.Select <tttorder>().Limit(2).ToList(); var tsql1 = fsql.Select <Sys_reg_user>() .Include(a => a.Owner) .Where(a => a.UnionId == "xxx") .ToSql(); var tsql2 = fsql.Select <Sys_owner>() .Where(a => a.RegUser.UnionId == "xxx2") .ToSql(); var names = (fsql.Select <object>() as Select0Provider)._commonUtils.SplitTableName("`Backups.ProductStockBak`"); var dbparams = fsql.Ado.GetDbParamtersByObject(new { id = 1, name = "xxx" }); var sql = fsql.CodeFirst.GetComparisonDDLStatements(typeof(EMSServerModel.Model.User), "testxsx001"); var test01 = EMSServerModel.Model.User.Select.IncludeMany(a => a.Roles).ToList(); var test02 = EMSServerModel.Model.UserRole.Select.ToList(); var test01tb = EMSServerModel.Model.User.Orm.CodeFirst.GetTableByEntity(typeof(EMSServerModel.Model.User)); var us = User1.Select.Limit(10).ToList(); new Products { title = "product-1" }.Save(); new Products { title = "product-2" }.Save(); new Products { title = "product-3" }.Save(); new Products { title = "product-4" }.Save(); new Products { title = "product-5" }.Save(); var wdy1 = JsonConvert.DeserializeObject <DynamicFilterInfo>(@" { ""Logic"" : ""And"", ""Filters"" : [ { ""Logic"" : ""Or"", ""Filters"" : [ { ""Field"" : ""title"", ""Operator"" : ""contains"", ""Value"" : """", }, { ""Field"" : ""title"", ""Operator"" : ""contains"", ""Value"" : ""product-2222"", } ] }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-2"" }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-3"" }, { ""Field"" : ""title"", ""Operator"" : ""eq"", ""Value"" : ""product-4"" }, { ""Field"" : ""testint"", ""Operator"" : ""Range"", ""Value"" : [100,200] }, { ""Field"" : ""testint"", ""Operator"" : ""Range"", ""Value"" : [""101"",""202""] }, { ""Field"" : ""testint"", ""Operator"" : ""contains"", ""Value"" : ""123"" }, ] } "); var config = new JsonSerializerOptions() { PropertyNamingPolicy = null, AllowTrailingCommas = true, IgnoreNullValues = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Converters = { new JsonStringEnumConverter() } }; var wdy2 = System.Text.Json.JsonSerializer.Deserialize <DynamicFilterInfo>(@" { ""Logic"" : 1, ""Filters"" : [ { ""Field"" : ""title"", ""Operator"" : 8, ""Value"" : ""product-1"", ""Filters"" : [ { ""Field"" : ""title"", ""Operator"" : 0, ""Value"" : ""product-1111"" } ] }, { ""Field"" : ""title"", ""Operator"" : 8, ""Value"" : ""product-2"" }, { ""Field"" : ""title"", ""Operator"" : 8, ""Value"" : ""product-3"" }, { ""Field"" : ""title"", ""Operator"" : 8, ""Value"" : ""product-4"" }, { ""Field"" : ""testint"", ""Operator"" : 8, ""Value"" : 11 }, { ""Field"" : ""testint"", ""Operator"" : 8, ""Value"" : ""12"" }, { ""Field"" : ""testint"", ""Operator"" : ""Range"", ""Value"" : [100,200] }, { ""Field"" : ""testint"", ""Operator"" : ""Range"", ""Value"" : [""101"",""202""] } ] } ", config); Products.Select.WhereDynamicFilter(wdy1).ToList(); Products.Select.WhereDynamicFilter(wdy2).ToList(); var items1 = Products.Select.Limit(10).OrderByDescending(a => a.CreateTime).ToList(); var items2 = fsql.Select <Products>().Limit(10).OrderByDescending(a => a.CreateTime).ToList(); BaseEntity.Orm.UseJsonMap(); BaseEntity.Orm.UseJsonMap(); BaseEntity.Orm.CodeFirst.ConfigEntity <S_SysConfig <TestConfig> >(a => { a.Property(b => b.Config2).JsonMap(); }); new S_SysConfig <TestConfig> { Name = "testkey11", Config = new TestConfig { clicks = 11, title = "testtitle11" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey22", Config = new TestConfig { clicks = 22, title = "testtitle22" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); new S_SysConfig <TestConfig> { Name = "testkey33", Config = new TestConfig { clicks = 33, title = "testtitle33" }, Config2 = new TestConfig { clicks = 11, title = "testtitle11" } }.Save(); var testconfigs11 = S_SysConfig <TestConfig> .Select.ToList(); var testconfigs11tb = S_SysConfig <TestConfig> .Select.ToDataTable(); var testconfigs111 = S_SysConfig <TestConfig> .Select.ToList(a => a.Name); var testconfigs112 = S_SysConfig <TestConfig> .Select.ToList(a => a.Config); var testconfigs1122 = S_SysConfig <TestConfig> .Select.ToList(a => new { a.Name, a.Config }); var testconfigs113 = S_SysConfig <TestConfig> .Select.ToList(a => a.Config2); var testconfigs1133 = S_SysConfig <TestConfig> .Select.ToList(a => new { a.Name, a.Config2 }); var repo = BaseEntity.Orm.Select <TestConfig>().Limit(10).ToList(); //void ConfigEntityProperty(object sender, FreeSql.Aop.ConfigEntityPropertyEventArgs e) //{ // if (e.Property.PropertyType == typeof(byte[])) // { // var orm = sender as IFreeSql; // switch (orm.Ado.DataType) // { // case DataType.SqlServer: // e.ModifyResult.DbType = "image"; // break; // case DataType.MySql: // e.ModifyResult.DbType = "longblob"; // break; // } // } //} //fsql.Aop.ConfigEntityProperty += ConfigEntityProperty; Task.Run(async() => { using (var uow = BaseEntity.Orm.CreateUnitOfWork()) { _asyncUow.Value = uow; try { var id = (await new User1().SaveAsync()).Id; } finally { _asyncUow.Value = null; } uow.Commit(); } var ug1 = new UserGroup(); ug1.GroupName = "分组一"; await ug1.InsertAsync(); var ug2 = new UserGroup(); ug2.GroupName = "分组二"; await ug2.InsertAsync(); var u1 = new User1(); u1.GroupId = ug1.Id; await u1.SaveAsync(); await u1.DeleteAsync(); await u1.RestoreAsync(); u1.Nickname = "x1"; await u1.UpdateAsync(); var u11 = await User1.FindAsync(u1.Id); u11.Description = "备注"; await u11.SaveAsync(); await u11.DeleteAsync(); var slslsl = Newtonsoft.Json.JsonConvert.SerializeObject(u1); var u11null = User1.Find(u1.Id); var u11s = User1.Where(a => a.Group.Id == ug1.Id).Limit(10).ToList(); var u11s2 = User1.Select.LeftJoin <UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList(); var ug1s = UserGroup.Select .IncludeMany(a => a.User1s) .Limit(10).ToList(); var ug1s2 = UserGroup.Select.Where(a => a.User1s.AsSelect().Any(b => b.Nickname == "x1")).Limit(10).ToList(); var r1 = new Role(); r1.Id = "管理员"; await r1.SaveAsync(); var r2 = new Role(); r2.Id = "超级会员"; await r2.SaveAsync(); var ru1 = new RoleUser1(); ru1.User1Id = u1.Id; ru1.RoleId = r1.Id; await ru1.SaveAsync(); ru1.RoleId = r2.Id; await ru1.SaveAsync(); var u1roles = await User1.Select.IncludeMany(a => a.Roles).ToListAsync(); var u1roles2 = await User1.Select.Where(a => a.Roles.AsSelect().Any(b => b.Id == "xx")).ToListAsync(); }).Wait(); Console.WriteLine("按任意键结束。。。"); Console.ReadKey(); }