### Query Data Example Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started A C# example demonstrating how to query a collection of Blog entities with filtering, ordering, skipping, and limiting. ```csharp var blogs = fsql.Select() .Where(b => b.Rating > 3) .OrderBy(b => b.Url) .Skip(100) .Limit(10) //Query the record from line 100 to line 110 .ToList(); ``` -------------------------------- ### Insert Data Example Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started A C# example showing how to insert a new Blog entity into the database and retrieve its auto-generated identity value. ```csharp var blog = new Blog { Url = "http://sample.com" }; blog.BlogId = (int)fsql.Insert() .AppendData(blog) .ExecuteIdentity(); ``` -------------------------------- ### Update Data Example Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started A C# example demonstrating how to update existing Blog entities in the database based on a condition and return the number of affected rows. ```csharp fsql.Update() .Set(b => b.Url, "http://sample2222.com") .Where(b => b.Url == "http://sample.com") .ExecuteAffrows(); ``` -------------------------------- ### Delete Data Example Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started A C# example showing how to delete Blog entities from the database based on a condition and return the number of affected rows. ```csharp fsql.Delete() .Where(b => b.Url == "http://sample.com") .ExecuteAffrows(); ``` -------------------------------- ### Install FreeSql Packages Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started Commands to add FreeSql and a specific provider (Sqlite) to a .NET project using the dotnet CLI or Package Manager Console. ```bash dotnet add packages FreeSql dotnet add packages FreeSql.Provider.Sqlite ``` ```powershell Install-Package FreeSql Install-Package FreeSql.Provider.Sqlite ``` -------------------------------- ### Quick Start Source: https://github.com/dotnetcore/freesql/blob/master/README.md Example of setting up FreeSql with SQLite and defining entities. ```csharp static IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=document.db") .UseAutoSyncStructure(true) //automatically synchronize the entity structure to the database .Build(); //be sure to define as singleton mode class Song { [Column(IsIdentity = true)] public int Id { get; set; } public string Title { get; set; } public string Url { get; set; } public DateTime CreateTime { get; set; } public ICollection Tags { get; set; } } class Song_tag { public int Song_id { get; set; } public Song Song { get; set; } public int Tag_id { get; set; } public Tag Tag { get; set; } } class Tag { [Column(IsIdentity = true)] public int Id { get; set; } public string Name { get; set; } public int? Parent_id { get; set; } public Tag Parent { get; set; } public ICollection Songs { get; set; } public ICollection Tags { get; set; } } ``` -------------------------------- ### Install FreeSql.Repository Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Install the FreeSql.Repository package using the .NET CLI. ```bash dotnet add package FreeSql.Repository ``` -------------------------------- ### Install Packages Source: https://github.com/dotnetcore/freesql/blob/master/Extensions/FreeSql.Extensions.BaseEntity/README.MD Install the necessary packages for FreeSql.Extensions.BaseEntity and a database provider. ```bash dotnet add package FreeSql.Extensions.BaseEntity dotnet add package FreeSql.Provider.Sqlite ``` -------------------------------- ### Sharding Example (Table Splitting) Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Example of creating a sharded repository for logs, splitting by year and month. ```csharp var logRepository = fsql.GetGuidRepository(null, oldname => $"{oldname}_{DateTime.Now.ToString("YYYYMM")}"); ``` -------------------------------- ### Installation Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.DbContext/readme.md Install the FreeSql.DbContext package using the dotnet add package command. ```bash dotnet add package FreeSql.DbContext ``` -------------------------------- ### WithSql Example Source: https://github.com/dotnetcore/freesql/wiki/Return-Data Illustrates how to use `WithSql` to execute a raw SQL query as a subquery, with an example of pagination. ```csharp fsql.Select() .WithSql("select * from Topic where clicks > @val", new { val = 10 }) .Page(1, 10) .ToList() //SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` //FROM (select * from Topic where clicks > @val) a ``` -------------------------------- ### Install FreeSql.Extensions.Linq Source: https://github.com/dotnetcore/freesql/wiki/Linq-to-Sql Command to install the FreeSql.Extensions.Linq package for FreeSql v1.4.0+. ```bash dotnet add package FreeSql.Extensions.Linq ``` -------------------------------- ### .NET Core Singleton IFreeSql Declaration Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started Example of how to register IFreeSql as a singleton service in .NET Core's Startup.cs, configuring it with a connection string and enabling automatic structure synchronization. ```csharp services.AddSingleton(r => { IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=db1.db") //Automatically synchronize the entity structure to the database. //FreeSql will not scan the assembly, and will generate a table if and only when the CRUD instruction is executed. .UseAutoSyncStructure(true) .Build(); return fsql; }); ``` -------------------------------- ### UnitOfWork Dependency Injection Setup Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Setup for injecting UnitOfWork and UnitOfWorkRepository into the service collection. ```csharp //第一步: public class UnitOfWorkRepository : BaseRepository { public UnitOfWorkRepository(IFreeSql fsql, IUnitOfWork uow) : base(fsql, null, null) { this.UnitOfWork = uow; } } public class UnitOfWorkRepository : BaseRepository { public UnitOfWorkRepository(IFreeSql fsql, IUnitOfWork uow) : base(fsql, null, null) { this.UnitOfWork = uow; } } //第二步: public void ConfigureServices(IServiceCollection services) { services.AddSingleton(fsql); services.AddScoped(sp => fsql.CreateUnitOfWork()); services.AddScoped(typeof(IReadOnlyRepository<>), typeof(UnitOfWorkRepository<>)); services.AddScoped(typeof(IBasicRepository<>), typeof(UnitOfWorkRepository<>)); services.AddScoped(typeof(BaseRepository<>), typeof(UnitOfWorkRepository<>)); services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(UnitOfWorkRepository<,>)); services.AddScoped(typeof(IBasicRepository<,>), typeof(UnitOfWorkRepository<,>)); services.AddScoped(typeof(BaseRepository<,>), typeof(UnitOfWorkRepository<,>)); //批量注入程序集内的所有自建仓储类,可以根据自己需要来修改 Assembly[] assemblies = new [] { typeof(XxxRepository).Assembly }; if (assemblies?.Any() == true) foreach (var asse in assemblies) foreach (var repo in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(UnitOfWorkRepository).IsAssignableFrom(a))) services.AddScoped(repo); } ``` -------------------------------- ### Join Example Source: https://github.com/dotnetcore/freesql/wiki/Linq-to-Sql Examples of performing inner joins between tables. ```csharp var t1 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId select a ).ToList(); var t2 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId select new { a.id, bid = b.id } ).ToList(); var t3 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId where a.id == item.id select new { a.id, bid = b.id } ).ToList(); ``` -------------------------------- ### Install FreeSql.Generator Source: https://github.com/dotnetcore/freesql/wiki/DbFirst Installs the FreeSql.Generator tool globally using the .NET Core CLI. ```dotnetcli dotnet tool install -g FreeSql.Generator ``` -------------------------------- ### FreeSql.Generator Example Source: https://github.com/dotnetcore/freesql/wiki/DbFirst Example command for FreeSql.Generator using various options including the -DB parameter. ```bash FreeSql.Generator -Razor 1 -NameOptions 0,0,0,1 -NameSpace LinCms.Core.Entities -DB "MySql,Data Source=127.0.0.1;Port=3306;User ID=root;Password=123456;Initial Catalog=lincms;Charset=utf8;SslMode=none;Max pool size=2" ``` -------------------------------- ### Accessing MySQL Database Example Source: https://github.com/dotnetcore/freesql/blob/master/Providers/FreeSql.Provider.Custom/readme.md Example demonstrating how to configure FreeSql to access a MySQL database using the Custom provider. ```csharp var fsql = new FreeSqlBuilder() .UseConnectionFactory(DataType.CustomMySql, () => new MySqlConnection("Data Source=...")) .UseNoneCommandParameter(true) .UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText)) .Build(); fsql.SetDbProviderFactory(MySqlConnectorFactory.Instance); ``` -------------------------------- ### Install FreeSql Provider for SQL Server Source: https://github.com/dotnetcore/freesql/wiki/Dapper比较 Command to install the FreeSql SQL Server provider package. ```bash dotnet add packages FreeSql.Provider.SqlServer ``` ```powershell Install-Package FreeSql.Provider.SqlServer ``` -------------------------------- ### CaseWhen Example Source: https://github.com/dotnetcore/freesql/wiki/Linq-to-Sql Example demonstrating the use of 'CaseWhen' logic within a select statement. ```csharp var t1 = ( from a in fsql.Select() where a.id == item.id select new { a.id, a.name, testsub = new { time = a.age > 10 ? "大于" : "小于或等于" } } ).ToList(); ``` -------------------------------- ### FreeSql.Generator Command Example Source: https://github.com/dotnetcore/freesql/wiki/DbFirst An example command demonstrating how to use FreeSql.Generator to generate entity classes with specific options. ```bash FreeSql.Generator -Razor 1 -NameOptions 0,0,0,0 -NameSpace MyProject -DB "MySql,Data Source=127.0.0.1;..." ``` -------------------------------- ### Install FreeSql Packages Source: https://github.com/dotnetcore/freesql/wiki/Install Command to add the FreeSql core package, the DbContext package, and the MySqlConnector provider package using the .NET CLI. ```bash dotnet add package FreeSql dotnet add package FreeSql.DbContext dotnet add package FreeSql.Provider.MySqlConnector ``` -------------------------------- ### Custom Adapter Example for MSSQL2000 Source: https://github.com/dotnetcore/freesql/blob/master/Providers/FreeSql.Provider.Custom/readme.md Example of creating a custom adapter for MSSQL2000 by inheriting from FreeSql.Custom.CustomAdapter. ```csharp class Mssql2000Adapter : FreeSql.Custom.CustomAdapter { public override string InsertAfterGetIdentitySql => "SELECT SCOPE_IDENTITY()"; //可以重写更多的设置 } static IFreeSql fsql = new FreeSqlBuilder() .UseConnectionString(DataType.Custom, () => new SqlConnection(@"Data Source=...")) .Build(); //be sure to define as singleton mode fsql.SetCustomAdapter(new Mssql2000Adapter()); ``` -------------------------------- ### Install FreeSql.DbContext for .NET Framework Source: https://github.com/dotnetcore/freesql/wiki/Repository Command to install the FreeSql.DbContext package for .NET Framework environments. ```bash Install-Package FreeSql.DbContext ``` -------------------------------- ### Repository Example Source: https://github.com/dotnetcore/freesql/blob/master/README.md Example of using the repository pattern with FreeSql, including transactional operations. ```csharp [Transactional] public void Add() { var repo = ioc.GetService>(); repo.DbContextOptions.EnableCascadeSave = true; var item = new Tag { Name = "testaddsublist", Tags = new[] { new Tag { Name = "sub1" }, new Tag { Name = "sub2" } } }; repo.Insert(item); } ``` -------------------------------- ### Example of using Ioc + Login Information for Auditing Source: https://github.com/dotnetcore/freesql/wiki/Repository Example demonstrating how to use dependency injection and login information to automatically populate audit fields during insert/update operations. ```csharp services.AddSingleton(fsql); services.AddScoped(r => new MyRepositoryOptions { AuditValue = e => { var user = r.GetService(); if (user == null) return; if (e.AuditValueType == AuditValueType.Insert && e.Object is IEntityCreated obj1 && obj1 != null) { obj1.CreatedUserId = user.Id; obj1.CreatedUserName = user.Username; } if (e.AuditValueType == AuditValueType.Update && e.Object is IEntityModified obj2 && obj2 != null) { obj2.ModifiedUserId = user.Id; obj2.ModifiedUserName = user.Username; } } }); services.AddScoped(typeof(IBaseRepository<>), typeof(MyRepository<>)); services.AddScoped(typeof(IBaseRepository<,>), typeof(MyRepository<,>)); //以下实现 MyRepository class MyRepository : BaseRepository where TEntity : class { public MyRepository(IFreeSql fsql, MyRepositoryOptions options) : base(fsql, null, null) { if (options?.AuditValue != null) DbContextOptions.AuditValue += (_, e) => options.AuditValue(e); } } class MyRepository : MyRepository where TEntity : class { public MyRepository(IFreeSql fsql, MyRepositoryOptions options) : base(fsql, options) { } } class MyRepositoryOptions { public Action AuditValue { get; set; } } ``` -------------------------------- ### Get Repository using extension method Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Get a repository instance for the Song entity using the extension method on IFreeSql. ```csharp var curd = fsql.GetRepository(); ``` -------------------------------- ### LeftJoin Example Source: https://github.com/dotnetcore/freesql/wiki/Linq-to-Sql Examples of performing left joins (including DefaultIfEmpty) between tables. ```csharp var t1 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId into temp from tc in temp.DefaultIfEmpty() select a ).ToList(); var t2 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId into temp from tc in temp.DefaultIfEmpty() select new { a.id, bid = tc.id } ).ToList(); var t3 = ( from a in fsql.Select() join b in fsql.Select() on a.id equals b.StudentId into temp from tc in temp.DefaultIfEmpty() where a.id == item.id select new { a.id, bid = tc.id } ).ToList(); ``` -------------------------------- ### DbContext Usage Example Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.DbContext/readme.md Example demonstrating adding, updating, and removing entities using DbContext, followed by SaveChangesAsync. ```csharp long id = 0; using (var ctx = new SongContext()) { var song = new Song { }; await ctx.Songs.AddAsync(song); id = song.Id; var adds = Enumerable.Range(0, 100) .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) .ToList(); await ctx.Songs.AddRangeAsync(adds); for (var a = 0; a < adds.Count; a++) adds[a].Title = "dkdkdkdk" + a; ctx.Songs.UpdateRange(adds); ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); //ctx.Songs.Update(adds.First()); adds.Last().Url = "skldfjlksdjglkjjcccc"; ctx.Songs.Update(adds.Last()); //throw new Exception("回滚"); await ctx.SaveChangesAsync(); } ``` -------------------------------- ### Blog Entity Model Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started An example of a C# entity class representing a database table, with FreeSql specific annotations for identity and primary key. ```csharp using FreeSql.DataAnnotations; using System; public class Blog { [Column(IsIdentity = true, IsPrimary = true)] public int BlogId { get; set; } public string Url { get; set; } public int Rating { get; set; } } ``` -------------------------------- ### .NET Framework Singleton IFreeSql Declaration Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started Example of declaring a static singleton instance of IFreeSql for use in .NET Framework applications, using Lazy for thread-safe initialization. ```csharp public class DB { static Lazy sqliteLazy = new Lazy(() => { var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=db1.db") .UseAutoSyncStructure(true) .Build(); return fsql; }); public static IFreeSql Sqlite => sqliteLazy.Value; } ``` -------------------------------- ### Basic Repository Initialization Source: https://github.com/dotnetcore/freesql/wiki/Repository-Layer Initializes User and Topic repositories. ```csharp var userRepository = fsql.GetRepository(); var topicRepository = fsql.GetRepository(); ``` -------------------------------- ### User with Guid primary key Source: https://github.com/dotnetcore/freesql/wiki/BaseEntity Example of defining a User entity with a Guid primary key, which will automatically generate an ordered, unique Guid value upon saving. ```csharp public class User : BaseEntity { public string UserName { get; set; } } ``` -------------------------------- ### Getting DbContext in MVC Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.DbContext/readme.md Example of injecting DbContext into an MVC controller. ```csharp IFreeSql _orm; public ValuesController(SongContext songContext) { } ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Configure dependency injection for IFreeSql and FreeSql.Repository, including global filters. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Fsql); services.AddFreeRepository(filter => filter .Apply("SoftDelete", a => a.IsDeleted == false) .Apply("Tenant", a => a.TenantId == 1) , this.GetType().Assembly ); } //在控制器使用 public SongsController(GuidRepository repos1) { } ``` -------------------------------- ### Install and Use JsonMap Extension Source: https://github.com/dotnetcore/freesql/blob/master/Extensions/FreeSql.Extensions.JsonMap/README.MD Instructions for installing the FreeSql.Extensions.JsonMap package and enabling the JsonMap functionality. Includes an example of mapping a complex object to a string column using the JsonMap attribute. ```csharp fsql.UseJsonMap(); //Turn on function class TestConfig { public int clicks { get; set; } public string title { get; set; } } [Table(Name = "sysconfig")] public class S_SysConfig { [Column(IsPrimary = true)] public string Name { get; set; } [JsonMap] public T Config { get; set; } } ``` -------------------------------- ### JsonMap Usage Source: https://github.com/dotnetcore/freesql/wiki/类型映射 Example of using FreeSql's JsonMap feature to map C# objects to JSON columns in the database. Includes installation command, attribute usage, and query example. ```csharp fsql.UseJsonMap(); //开启功能 class Table { public int Id { get; set; } [JsonMap] public TableOptions Options { get; set; } } class TableOptions { public int Value1 { get; set; } public string Value2 { get; set; } } fsql.Select().Where(a => a.Options.Value1 == 100 && a.Options.Value2 == "xx").ToList(); //WHERE json_extract(a."Options",'$.Value1') = 100 AND json_extract(a."Options",'$.Value2') = 'xx' ``` -------------------------------- ### BenchmarkDotNet Configuration Source: https://github.com/dotnetcore/freesql/wiki/Dapper比较 Configuration details for the BenchmarkDotNet performance tests. ```shell BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19044 Intel Core i7-8700K CPU 3.70GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores .NET Core SDK=6.0.100 [Host] : .NET Core 5.0.11 (CoreCLR 5.0.1121.47308, CoreFX 5.0.1121.47308), X64 RyuJIT DEBUG Job-LEQVAV : .NET Core 5.0.11 (CoreCLR 5.0.1121.47308, CoreFX 5.0.1121.47308), X64 RyuJIT DEBUG BuildConfiguration=Debug InvocationCount=1 UnrollFactor=1 ``` -------------------------------- ### Distinct count of a field Source: https://github.com/dotnetcore/freesql/wiki/Group-Aggregation-Query Example of how to get the distinct count of a specific field using the Aggregate method. ```csharp var list = fsql.Select() .Aggregate(a => Convert.ToInt32("count(distinct title)"), out var count) .ToList(); ``` -------------------------------- ### Aggregate without Grouping Source: https://github.com/dotnetcore/freesql/wiki/Group-Aggregation-Query Example of using ToAggregate to get aggregate values without explicit grouping. ```csharp var list = fsql.Select() .ToAggregate(a => new { cou1 = a.Count(), arg1 = a.Avg(a.Key.Clicks), arg2 = a.Sum(a.Key.Clicks > 100 ? 1 : 0) }); ``` -------------------------------- ### Distinct count using SqlExt.DistinctCount Source: https://github.com/dotnetcore/freesql/wiki/Group-Aggregation-Query Example of how to get the distinct count of a specific field using the SqlExt.DistinctCount extension method. ```csharp fsql.Select() .Aggregate(a => SqlExt.DistinctCount(a.Key.Title), out var count); ``` ```sql SELECT count(distinct a."title") as1 FROM "Topic" a ``` -------------------------------- ### Oracle Stored Procedure to get DataTable Source: https://github.com/dotnetcore/freesql/wiki/ADO Example of executing an Oracle stored procedure that returns a RefCursor and retrieving it as a DataTable. ```csharp OracleParameter p2 = null; var dt = fsql.Ado.CommandFluent("getTableInfo") .CommandType(CommandType.StoredProcedure) .CommandTimeout(60) .WithParameter("out_var", null, p => { p2 = p as OracleParameter; p2.OracleDbType = OracleDbType.RefCursor; p2.Direction = ParameterDirection.Output; }) .ExecuteDataTable(); Console.WriteLine(dt.Rows.Count); ``` -------------------------------- ### IOC + Login: Dependency Injection Setup Source: https://github.com/dotnetcore/freesql/wiki/Repository-Layer Example of integrating IOC with login information for automatic audit value population during insert/update operations. ```csharp services.AddSingleton(fsql); services.AddScoped(r => new MyRepositoryOptions { AuditValue = e => { var user = r.GetService(); if (user == null) return; if (e.AuditValueType == AuditValueType.Insert && e.Object is IEntityCreated obj1 && obj1 != null) { obj1.CreatedUserId = user.Id; obj1.CreatedUserName = user.Username; } if (e.AuditValueType == AuditValueType.Update && e.Object is IEntityModified obj2 && obj2 != null) { obj2.ModifiedUserId = user.Id; obj2.ModifiedUserName = user.Username; } } }); services.AddScoped(typeof(IBaseRepository<>), typeof(MyRepository<>)); services.AddScoped(typeof(IBaseRepository<,>), typeof(MyRepository<,>)); class MyRepository : BaseRepository where TEntity : class { public MyRepository(IFreeSql fsql, MyRepositoryOptions options) : base(fsql, null, null) { if (options?.AuditValue != null) DbContextOptions.AuditValue += (_, e) => options.AuditValue(e); } } class MyRepository : MyRepository where TEntity : class { public MyRepository(IFreeSql fsql, MyRepositoryOptions options) : base(fsql, options) { } } class MyRepositoryOptions { public Action AuditValue { get; set; } } ``` -------------------------------- ### Basic IFreeSql Operations Source: https://github.com/dotnetcore/freesql/wiki/Getting-Started Illustrates the primary methods available on the IFreeSql interface for common ORM operations like Query, Insert, Update, Delete, and Transaction. ```csharp fsql.Select(); //Query fsql.Insert(); //Insert fsql.Update(); //Update fsql.Delete(); //Delete fsql.InsertOrUpdate()// Insert or Update fsql.Transaction(..); //Transaction fsql.CodeFirst; //CodeFirst Object fsql.DbFirst; //DbFirst Object fsql.Ado; //Ado Object fsql.Aop; //Aop Object fsql.GlobalFilter; //Gloabl Filter Object ``` -------------------------------- ### Get Entity Types by Namespace Source: https://github.com/dotnetcore/freesql/wiki/CodeFirst A method to retrieve entity types from a specific assembly based on their namespace, filtering for classes that start with specified namespace prefixes. ```csharp public static Type[] GetTypesByNameSpace() { List tableAssembies = new List(); List entitiesFullName = new List() { "LinCms.Entities.Settings", "LinCms.Entities.Base", }; foreach (Type type in Assembly.GetAssembly(typeof(IEntity)).GetExportedTypes()) foreach (var fullname in entitiesFullName) if (type.FullName.StartsWith(fullname) && type.IsClass) tableAssembies.Add(type); return tableAssembies.ToArray(); } //或通过调用同步所有表结构 fsql.CodeFirst.SyncStructure(GetTypesByNameSpace()); ``` -------------------------------- ### FreeSql Initialization Source: https://github.com/dotnetcore/freesql/wiki/Unit-of-Work Example of initializing FreeSql with connection string and enabling automatic structure synchronization. It's recommended to define it as a singleton. ```csharp static IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connectionString) //Automatically synchronize the entity structure to the database. .UseAutoSyncStructure(true) //Be sure to define as singleton mode .Build(); ``` -------------------------------- ### Initialization Source: https://github.com/dotnetcore/freesql/blob/master/Extensions/FreeSql.Extensions.BaseEntity/README.MD Initialize BaseEntity with the FreeSql instance. ```csharp BaseEntity.Initialization(fsql, null); ``` -------------------------------- ### Display FreeSql.Generator Help Source: https://github.com/dotnetcore/freesql/wiki/DbFirst Displays the help information for the FreeSql.Generator command-line tool. ```dotnetcli FreeSql.Generator --help ``` -------------------------------- ### Where Clause Example Source: https://github.com/dotnetcore/freesql/wiki/Linq-to-Sql Example of using a 'where' clause in a Linq query. ```csharp var t1 = ( from a in fsql.Select() where a.id == item.id select a ).ToList(); ``` -------------------------------- ### Get AggregateRootRepository Source: https://github.com/dotnetcore/freesql/wiki/聚合根(实验室) Get an instance of AggregateRootRepository for a specific entity. ```csharp var repository = fsql.GetAggregateRootRepository(); ``` -------------------------------- ### Query Examples Source: https://github.com/dotnetcore/freesql/blob/master/README.md Demonstrates various querying capabilities including OneToOne, ManyToOne, OneToMany, ManyToMany, and conditional queries. ```csharp //OneToOne、ManyToOne fsql.Select().Where(a => a.Parent.Parent.Name == "English").ToList(); //OneToMany fsql.Select().IncludeMany(a => a.Tags, then => then.Where(sub => sub.Name == "foo")).ToList(); //ManyToMany fsql.Select() .IncludeMany(a => a.Tags, then => then.Where(sub => sub.Name == "foo")) .Where(s => s.Tags.Any(t => t.Name == "Chinese")) .ToList(); //Other fsql.Select() .Where(a => a.IsDelete == 0) .WhereIf(keyword != null, a => a.UserName.Contains(keyword)) .WhereIf(role_id > 0, a => a.RoleId == role_id) .Where(a => a.Nodes.Any(t => t.Parent.Id == t.UserId)) .Count(out var total) .Page(page, size) .OrderByDescending(a => a.Id) .ToList() ``` ```csharp fsql.Select().Where(a => new[] { 1, 2, 3 }.Contains(a.Id)).ToList(); fsql.Select().Where(a => a.CreateTime.Date == DateTime.Today).ToList(); fsql.Select().OrderBy(a => Guid.NewGuid()).Limit(10).ToList(); fsql.Select().ToList(a => new { a.Id, Tags = fsql.Select().ToList(), SongTags = fsql.Select().Where(b => b.TopicId == a.Id).ToList() }); ``` -------------------------------- ### FreeSql Initialization and Topic Class Definition Source: https://github.com/dotnetcore/freesql/wiki/分页查询 Initializes FreeSql as a singleton and defines the Topic entity class. ```csharp static IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connectionString) .Build(); //请务必定义成 Singleton 单例模式 class Topic { [Column(IsIdentity = true)] public int Id { get; set; } public string Title { get; set; } public int Clicks { get; set; } public DateTime CreateTime { get; set; } public int CategoryId { get; set; } } ``` -------------------------------- ### Initialize FreeSql Source: https://github.com/dotnetcore/freesql/wiki/DbFirst Initializes FreeSql as a Singleton instance, essential for its proper functioning. ```csharp static IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connectionString) .Build(); //请务必定义成 Singleton 单例模式 ``` -------------------------------- ### Filtering and Validation Example Source: https://github.com/dotnetcore/freesql/blob/master/FreeSql.Repository/readme.md Example of using filter expressions to secure data and validate input. ```csharp var userRepository = fsql.GetGuidRepository(); var topicRepository = fsql.GetGuidRepository(); var userRepository = fsql.GetGuidRepository(a => a.Id == 1); var topicRepository = fsql.GetGuidRepository(a => a.UserId == 1); ``` -------------------------------- ### Using WithSql for Raw SQL Queries Source: https://github.com/dotnetcore/freesql/wiki/返回数据 Demonstrates how to execute a raw SQL query with parameters using WithSql. ```csharp fsql.Select() .WithSql("select * from Topic where clicks > @val", new { val = 10 }) .Page(1, 10) .ToList() //SELECT a.`Id`, a.`Clicks`, a.`CategoryId`, a.`Title`, a.`CreateTime` //FROM (select * from Topic where clicks > @val) a ``` -------------------------------- ### Basic Read/Write Separation Configuration Source: https://github.com/dotnetcore/freesql/wiki/读写分离 Demonstrates how to configure FreeSql with a master database and multiple slave databases using `UseSlave`. It also shows how to explicitly read from the master database. ```csharp static IFreeSql fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connectionString) .UseSlave("connectionString1", "connectionString2") //使用从数据库,支持多个 //.UseSlaveWeight(10, 5) //读权重 v3.2.100 .Build(); //请务必定义成 Singleton 单例模式 fsql.Select().Where(a => a.Id == 1).ToOne(); //读【从库】(默认) fsql.Select().Master().WhereId(a => a.Id == 1).ToOne(); //强制读【主库】 fsql.Ado.Query("/*master*/ select * from t where ..."); //强制读【主库】 ``` -------------------------------- ### Define Entity with Guid Primary Key Source: https://github.com/dotnetcore/freesql/blob/master/Extensions/FreeSql.Extensions.BaseEntity/README.MD Define a User entity with a Guid primary key, which will be automatically generated. ```csharp public class User : BaseEntity { public string UserName { get; set; } } ``` -------------------------------- ### DB Parameter Reference Source: https://github.com/dotnetcore/freesql/wiki/DbFirst Example of the -DB parameter with a MySql connection string. ```bash -DB "MySql,Data Source=127.0.0.1;Port=3306;User ID=root;Password=123456;Initial Catalog=lincms;Charset=utf8;SslMode=none;Max pool size=2" ``` -------------------------------- ### MaxLength Attribute Example Source: https://github.com/dotnetcore/freesql/wiki/更新日志 Example demonstrating the MaxLength attribute for setting string length in entities. ```csharp class Topic { [MaxLength(128)] public string Title { get; set; } } ```