### Furion Tools CLI Command Parameter Reference Source: https://help.zhouy1.com/furion/docs/dbcontext-db-first This section provides a comprehensive reference for the command-line parameters supported by 'Furion Tools Cli'. Each parameter is described with its purpose, type, default value, and examples, guiding users on how to customize the entity generation process, including specifying tables, database context, connection names, output directories, and database providers. ```APIDOC -Tables: Configures database tables to be generated (array type). If empty, all tables and views are generated. E.g., -Tables Person,PersonDetails -Context: Configures the database context, default is FurionDbContext. Required if multiple contexts exist. -ConnectionName: Configures the database connection string, corresponding to the Key defined in appsetting.json's ConnectionStrings. -OutputDir: Output directory for generated entity code, default is ./Furion.Core/Entities/ -DbProvider: Database provider, default is Microsoft.EntityFrameworkCore.SqlServer. Other databases require specifying the corresponding assembly: + SqlServer: Microsoft.EntityFrameworkCore.SqlServer + Sqlite: Microsoft.EntityFrameworkCore.Sqlite + Cosmos: Microsoft.EntityFrameworkCore.Cosmos + InMemoryDatabase: Microsoft.EntityFrameworkCore.InMemory + MySql: Pomelo.EntityFrameworkCore.MySql or MySql.EntityFrameworkCore + PostgreSQL: Npgsql.EntityFrameworkCore.PostgreSQL + Oracle: Oracle.EntityFrameworkCore + Dm: Microsoft.EntityFrameworkCore.Dm -EntryProject: Web enabled project layer name, default Furion.Web.Entry -CoreProject: Entity project layer name, default Furion.Core -DbContextLocators: Multiple database context locators, default MasterDbContextLocator. Supports multiple, e.g., MasterDbContextLocator,MySqlDbContextLocator -Product: Solution default prefix, e.g., Furion -UseDatabaseNames: Whether to keep generated names consistent with database and table names -Namespace: Specifies the entity namespace ``` -------------------------------- ### Example Usage of Furion Tools CLI Script Source: https://help.zhouy1.com/furion/docs/dbcontext-db-first This PowerShell command demonstrates how to invoke the 'cli.ps1' script from Furion Tools. It shows the basic syntax for passing the database context name and connection string key as parameters. This command is used to initiate the entity generation process. ```PowerShell &"../tools/cli.ps1" -Context 数据库上下文名 -ConnectionName 连接字符串Key ``` -------------------------------- ### Override OnConfiguring for Dynamic Connection String (C#) Source: https://help.zhouy1.com/furion/docs/saas This C# example shows how to override the `OnConfiguring` method in a multi-tenant `DbContext` to dynamically configure the database connection string using `UseSqlite` and the `GetDatabaseConnectionString` method. It ensures the correct tenant-specific database is used. It also includes an example of specifying the migrations assembly for Code First with Database-per-tenant. ```C# using Furion.DatabaseAccessor; using Microsoft.EntityFrameworkCore; namespace Furion.EntityFramework.Core { public class FurionDbContext : AppDbContext, IMultiTenantOnDatabase { public FurionDbContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite(GetDatabaseConnectionString()); base.OnConfiguring(optionsBuilder); } public string GetDatabaseConnectionString() { return base.Tenant?.ConnectionString??"默认链接字符串"; } } } ``` ```C# optionsBuilder.UseSqlite(GetDatabaseConnectionString(), options=> { options.MigrationsAssembly("My.Migrations"); }); ``` -------------------------------- ### Furion Framework Log Output Example Source: https://help.zhouy1.com/furion/docs/logging This snippet showcases a typical log output template generated by the Furion framework. It includes informational messages about application startup, hosting environment, content root path, warnings regarding sensitive data logging and EF Core query splitting behavior, and detailed logs of executed SQL commands. ```Log 2020-12-21 15:54:43.775 +08:00 [INF] Application started. Press Ctrl+C to shut down. 2020-12-21 15:54:43.897 +08:00 [INF] Hosting environment: Development 2020-12-21 15:54:43.899 +08:00 [INF] Content root path: D:\MONK\Furion\samples\Furion.Web.Entry 2020-12-21 15:55:00.651 +08:00 [WRN] Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development. 2020-12-21 15:55:00.817 +08:00 [INF] Entity Framework Core 5.0.1 initialized 'DefaultDbContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: SensitiveDataLoggingEnabled DetailedErrorsEnabled MaxPoolSize=100 MigrationsAssembly=Furion.Database.Migrations 2020-12-21 15:55:01.711 +08:00 [WRN] Compiling a query which loads related collections for more than one collection navigation either via 'Include' or through projection but no 'QuerySplittingBehavior' has been configured. By default Entity Framework will use 'QuerySplittingBehavior.SingleQuery' which can potentially result in slow query performance. See https://go.microsoft.com/fwlink/?linkid=2134277 for more information. To identify the query that's triggering this warning call 'ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))' 2020-12-21 15:55:01.919 +08:00 [INF] Executed DbCommand (31ms) [Parameters=[], CommandType='"Text"', CommandTimeout='30'] SELECT "p"."Id", "p"."Name", "p"."Age", "p"."Address", "p0"."PhoneNumber", "p0"."QQ", "p"."CreatedTime", "p0"."Id", "c"."Id", "c"."Name", "c"."Gender", "t"."Id", "t"."Name", "t"."PersonsId", "t"."PostsId" FROM "Person" AS "p" LEFT JOIN "PersonDetail" AS "p0" ON "p"."Id" = "p0"."PersonId" LEFT JOIN "Children" AS "c" ON "p"."Id" = "c"."PersonId" LEFT JOIN ( SELECT "p2"."Id", "p2"."Name", "p1"."PersonsId", "p1"."PostsId" FROM "PersonPost" AS "p1" INNER JOIN "Post" AS "p2" ON "p1"."PostsId" = "p2"."Id" ) AS "t" ON "p"."Id" = "t"."PersonsId" ORDER BY "p"."Id", "p0"."Id", "c"."Id", "t"."PersonsId", "t"."PostsId", "t"."Id" 2020-12-21 15:55:25.354 +08:00 [INF] Executed DbCommand (3ms) [Parameters=[], CommandType='"Text"', CommandTimeout='30'] SELECT "p"."Id", "p"."Name", "p"."Age", "p"."Address", "p0"."PhoneNumber", "p0"."QQ", "p"."CreatedTime", "p0"."Id", "c"."Id", "c"."Name", "c"."Gender", "t"."Id", "t"."Name", "t"."PersonsId", "t"."PostsId" FROM "Person" AS "p" LEFT JOIN "PersonDetail" AS "p0" ON "p"."Id" = "p0"."PersonId" LEFT JOIN "Children" AS "c" ON "p"."Id" = "c"."PersonId" LEFT JOIN ( SELECT "p2"."Id", "p2"."Name", "p1"."PersonsId", "p1"."PostsId" FROM "PersonPost" AS "p1" INNER JOIN "Post" AS "p2" ON "p1"."PostsId" = "p2"."Id" ) AS "t" ON "p"."Id" = "t"."PersonsId" ORDER BY "p"."Id", "p0"."Id", "c"."Id", "t"."PersonsId", "t"."PostsId", "t"."Id" 2020-12-21 15:58:27.328 +08:00 [INF] Application started. Press Ctrl+C to shut down. 2020-12-21 15:58:27.442 +08:00 [INF] Hosting environment: Development 2020-12-21 15:58:27.444 +08:00 [INF] Content root path: D:\MONK\Furion\samples\Furion.Web.Entry 2020-12-21 15:58:27.909 +08:00 [INF] HTTP GET / responded 200 in 457.0657 ms 2020-12-21 15:58:33.336 +08:00 [INF] HTTP GET /api/index.html responded 200 in 95.9277 ms 2020-12-21 15:58:34.187 +08:00 [INF] HTTP GET /swagger/Default/swagger.json responded 200 in 674.9800 ms ``` -------------------------------- ### Furion Serilog - Custom Console and File Output Configuration Source: https://help.zhouy1.com/furion/docs/logging Provides an example of customizing Serilog's output to console and file. It demonstrates how to pass a configuration action to UseSerilogDefault() to define custom output templates and file rolling policies. ```C# .UseSerilogDefault(config => { config.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") .WriteTo.File("log.log", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true); }); ``` -------------------------------- ### Database Connection String Examples for Various Providers Source: https://help.zhouy1.com/furion/docs/dbcontext This section provides example connection strings for common database types supported by the Furion framework, including Sqlite, MySQL, SQL Server, Oracle, and PostgreSQL. These examples illustrate the typical format and parameters required for connecting to each database. ```Text Sqlite: Data Source=./Furion.db MySql: Data Source=localhost;Database=Furion;User ID=root;Password=000000;pooling=true;port=3306;sslmode=none;CharSet=utf8; SqlServer: Server=localhost;Database=Furion;User=sa;Password=000000;MultipleActiveResultSets=True; Oracle: User Id=orcl;Password=orcl;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl))) PostgreSQL: PORT=5432;DATABASE=postgres;HOST=127.0.0.1;PASSWORD=postgres;USER ID=postgres; ``` -------------------------------- ### Registering SqlSugar Setup in Startup.cs Source: https://help.zhouy1.com/furion/docs/sqlsugar This C# code shows how to register the SqlSugar services in the `Startup.cs` file (or equivalent configuration file in modern .NET applications) by calling the `AddSqlsugarSetup` extension method on the `IServiceCollection`, passing the application's configuration. ```C# services.AddSqlsugarSetup(App.Configuration); ``` -------------------------------- ### Install dotnet ef Global Tool (CLI) Source: https://help.zhouy1.com/furion/docs/dbcontext-code-first Installs the `dotnet ef` command-line interface tool globally. This tool is essential for managing Entity Framework Core migrations from any command prompt, providing a cross-platform alternative to the Visual Studio Package Manager Console. ```CLI dotnet tool install --global dotnet-ef --version 5.0.0-rc.2.20475.6 ``` -------------------------------- ### Building SQL Operations using Static Default Method in Furion (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-sql This example demonstrates an alternative way to construct and execute SQL queries using the static `SqlExecutePart.Default` method. It allows setting the SQL string and then executing the query. ```C# SqlExecutePart.Default.SetSqlString("select * from person").SqlQuery(); ``` -------------------------------- ### SqlSugar Pagination Query Source: https://help.zhouy1.com/furion/docs/sqlsugar This C# example demonstrates how to perform a pagination query using SqlSugar. It sets `pageIndex` and `pageSize`, then uses `ToPageList` on a `Queryable` to retrieve a specific page of results and the total count. ```C# int pageIndex = 1; int pageSize = 20; int totalCount=0; var page = db.Queryable().ToPageList(pageIndex, pageSize, ref totalCount); ``` -------------------------------- ### Examples of Short Parameters in .NET Tools Source: https://help.zhouy1.com/furion/docs/dotnet-tools Illustrates how short parameters are parsed. Examples include single-character parameters with and without values, and combinations of multiple short parameters. For `-a foo`, 'a' has value 'foo'. For `-ab`, 'a' and 'b' have no value. For `-abc bar`, 'a' and 'b' have no value, and 'c' has value 'bar'. ```Shell -a foo ``` ```Shell -ab ``` ```Shell -abc bar ``` -------------------------------- ### SqlSugar Singleton Database Context Source: https://help.zhouy1.com/furion/docs/sqlsugar Illustrates the implementation of a singleton pattern for the SqlSugar database context using SqlSugarScope. It includes configuration for a SQL Server connection and an AOP (Aspect-Oriented Programming) event for logging SQL execution. The example also shows how to use a transaction scope with the singleton instance for multiple operations. ```C# public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() { DbType = SqlSugar.DbType.SqlServer, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true }, db=> { db.Aop.OnLogExecuting = (s, p) => { Console.WriteLine(s); }; }); using (var tran = Db.UseTran()) { new Test2().Insert(XX); new Test1().Insert(XX); ..... tran.CommitTran(); } ``` -------------------------------- ### Add Tenant Seed Data for Furion Multi-Tenancy (C#) Source: https://help.zhouy1.com/furion/docs/saas Defines a `TenantSeedData` class implementing `IEntitySeedData` to pre-populate `Tenant` records in a multi-tenant database. This C# example shows how to configure initial tenant details, including connection strings, for a Code First approach. This step is only applicable for Code First scenarios. ```C# using Furion.DatabaseAccessor; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; namespace Furion.EntityFramework.Core { public class TenantSeedData : IEntitySeedData { public IEnumerable HasData(DbContext dbContext, Type dbContextLocator) { return new List { new Tenant { TenantId = Guid.Parse("383AFB88-F519-FFF8-B364-6D563BF3687F"), Name = "默认租户", Host = "localhost:44313", CreatedTime = DateTime.Parse("2020-10-06 20:19:07"), ConnectionString = "Data Source=./Furion.db" // 配置连接字符串 }, new Tenant { TenantId = Guid.Parse("C5798CB6-16D6-0F42-EB56-59C695353BC0"), Name = "其他租户", Host = "localhost:5000", CreatedTime = DateTime.Parse("2020-10-06 20:20:32"), ConnectionString = "Data Source=./Fur2.db" // 配置连接字符串 } }; } } } ``` -------------------------------- ### Define and Query Custom Tenant Class in Furion (C#) Source: https://help.zhouy1.com/furion/docs/saas Shows how to define a custom `Tenant` class (`MyTenant`) that implements `IEntity` with properties like `TenantId`, `Name`, and `Host`. It also provides an example of how to query instances of this custom tenant type from the `MultiTenantDbContextLocator` database context, demonstrating data retrieval for custom tenant models. ```C# using System; using System.ComponentModel.DataAnnotations.Schema; namespace Furion.Core { public class MyTenant : IEntity { [Key] public Guid TenantId { get; set; } public string Name { get; set; } public string Host { get; set; } } } ``` ```C# var tenantDbContext = Db.GetDbContext(); var myTenant = tenantDbContext.Set(); ``` -------------------------------- ### Creating a Basic Dynamic WebAPI Controller in Furion Source: https://help.zhouy1.com/furion/docs/dynamic-api-controller These C# examples illustrate two common ways to define a dynamic WebAPI controller in the Furion framework. Both methods achieve the same outcome: creating a simple `Get` endpoint that returns a string, demonstrating the flexibility of using either an interface or an attribute. ```C# using Furion.DynamicApiController; namespace Furion.Application { public class FurionAppService : IDynamicApiController { public string Get() { return $"Hello {nameof(Furion)}"; } } } ``` ```C# using Furion.DynamicApiController; namespace Furion.Application { [DynamicApiController] public class FurionAppService { public string Get() { return $"Hello {nameof(Furion)}"; } } } ``` -------------------------------- ### SqlSugar Setup: Creating an Extension Class for Service Collection Source: https://help.zhouy1.com/furion/docs/sqlsugar This C# code defines an extension class `SqlsugarSetup` to configure and add SqlSugar to the `IServiceCollection`. It sets up a `ConnectionConfig` for a MySQL database, retrieves the connection string from configuration, and configures AOP for logging SQL queries. The `SqlSugarScope` instance is registered as a singleton. ```C# public static class SqlsugarSetup { public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, string dbName = "db_master") { //如果多个数数据库传 List var configConnection=new ConnectionConfig() { DbType = SqlSugar.DbType.MySql, ConnectionString = configuration.GetConnectionString(dbName), IsAutoCloseConnection = true, }; SqlSugarScope sqlSugar = new SqlSugarScope(configConnection, db => { //单例参数配置,所有上下文生效 db.Aop.OnLogExecuting = (sql, pars) => { //Console.WriteLine(sql);//输出sql }; }); services.AddSingleton(sqlSugar);//这边是SqlSugarScope用AddSingleton } } ``` -------------------------------- ### Example Configuration for URL Templates in Furion Source: https://help.zhouy1.com/furion/docs/http Provides an example JSON configuration structure that defines the `Furion:Address` used in URL templates, enabling centralized management of base URLs. ```JSON { "Furion": { "Address": "https://www.furion.icu" } } ``` -------------------------------- ### Set Example Values for API Properties in Furion Swagger Source: https://help.zhouy1.com/furion/docs/specification-document This C# code demonstrates how to provide custom example values for properties in API models using XML documentation comments (`/// `). These examples are then displayed in the Swagger UI, providing more meaningful default values for various data types like integers, booleans, strings, and arrays. For object types, `/// "object"` can force display. ```C# /// /// 年龄 /// /// 13 [Required, Range(10, 110)] public int Age { get; set;} ``` -------------------------------- ### Furion Repository Basic Query Example Source: https://help.zhouy1.com/furion/docs/dbcontext-hight-query A simple example demonstrating a basic query using the Furion repository pattern. It retrieves a list of 'posts' where the 'Id' is greater than 10. ```C# var posts = repository.Where(u => u.Id > 10).ToList(); ``` -------------------------------- ### Execute Multiple SQL Queries and Return Tuple in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Demonstrates how to execute multiple SQL queries simultaneously and map their results to a C# `Tuple` of different types (e.g., `Person`, `Student`, `string`, `PersonDto`). This includes examples for both synchronous and asynchronous operations, with and without parameters. ```C# // ==== 同步操作 ==== // 示例一 var (persons, students) = @" select * from person; select * from student;".SqlQueries(); // 示例二 var (persons, students) = @" select * from person where Id > @id; select * from student where Name like @name;".SqlQueries(new {id = 1, name = "%furion%"}); // 示例三 var (persons, students, string, PersonDto) = @" select * from person; exec PROC_GetStudents(@id); select 'Furion'; select * from FN_GetPerson(@id);".SqlQueries(new {id = 1}); ``` ```C# // ==== 异步操作 ==== // 示例一 var (persons, students) = await @" select * from person; select * from student;".SqlQueriesAsync(); // 示例二 var (persons, students) = await @" select * from person where Id > @id; select * from student where Name like @name;".SqlQueriesAsync(new {id = 1, name = "%furion%"}); // 示例三 var (persons, students, string, PersonDto) = await @" select * from person; exec PROC_GetStudents(@id); select 'Furion'; select * from FN_GetPerson(@id);".SqlQueriesAsync(new {id = 1}); ``` -------------------------------- ### Execute Stored Procedure and Return List in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Illustrates how to execute a stored procedure and map its results directly to a `List` of a specified type (e.g., `Person`). Examples cover calling procedures with and without parameters, for both synchronous and asynchronous operations. ```C# // ==== 同步操作 ==== // 示例一 var persons = "PROC_Name".SqlProcedureQuery(); // 示例二 var persons = "PROC_Name".SqlProcedureQuery(new {id = 1}); // 示例三 var persons = "PROC_Name".SqlProcedureQuery(new {id = 1, age = 27}); ``` ```C# // ==== 异步操作 ==== // 示例一 var persons = await "PROC_Name".SqlProcedureQueryAsync(); // 示例二 var persons = await "PROC_Name".SqlProcedureQueryAsync(new {id = 1}); // 示例三 var persons = await "PROC_Name".SqlProcedureQueryAsync(new {id = 1, age = 27}); ``` -------------------------------- ### Manual Transaction Management - Basic Example Source: https://help.zhouy1.com/furion/docs/tran Illustrates how to manually open, commit, and handle rollbacks for a database transaction using `_testRepository.Database.BeginTransaction()`. This example shows inserting multiple entities and committing them within a transaction scope. Note that newer versions of the framework may handle rollbacks automatically. ```C# // 开启事务 using (var transaction = _testRepository.Database.BeginTransaction()) { try { _testRepository.Insert(new Blog { Url = "http://blogs.msdn.com/dotnet" }); _testRepository.SaveNow(); _testRepository.Insert(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); _testRepository.SaveNow(); var blogs = _testRepository.Entity .OrderBy(b => b.Url) .ToList(); // 提交事务 transaction.Commit(); } catch (Exception) { // 回滚事务 // transaction.RollBack(); // 新版本自动回滚了 } } ``` -------------------------------- ### Execute Stored Procedure and Return DataSet in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Shows how to call a stored procedure that returns multiple result sets, which are then encapsulated within a `DataSet` object. Examples include calling procedures with no parameters, single parameters, and multiple parameters, for both synchronous and asynchronous execution. ```C# // ==== 同步操作 ==== // 示例一 var dataSet = "PROC_Name".SqlProcedureQueries(); // 示例二 var dataSet = "PROC_Name".SqlProcedureQueries(new {id = 1}); // 示例三 var dataSet = "PROC_Name".SqlProcedureQueries(new {id = 1, age = 27}); ``` ```C# // ==== 异步操作 ==== // 示例一 var dataSet = await "PROC_Name".SqlProcedureQueriesAsync(); // 示例二 var dataSet = await "PROC_Name".SqlProcedureQueriesAsync(new {id = 1}); // 示例三 var dataSet = await "PROC_Name".SqlProcedureQueriesAsync(new {id = 1, age = 27}); ``` -------------------------------- ### Performing SQL Operations with IRepository in Furion (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Similar to other repository types, `IRepository` allows direct execution of SQL queries. This snippet shows a basic example of using `SqlQuery` with an entity-specific repository. ```C# var dataTable = personRepository.SqlQuery("select * from person"); ``` -------------------------------- ### Execute Stored Procedure and Return DataTable in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Demonstrates how to call a stored procedure and retrieve its results as a `DataTable` object. Examples include calling procedures with no parameters, single parameters, and multiple parameters, for both synchronous and asynchronous execution. ```C# // ==== 同步操作 ==== // 示例一 var dataTable = "PROC_Name".SqlProcedureQuery(); // 示例二 var dataTable = "PROC_Name".SqlProcedureQuery(new {id = 1}); // 示例三 var dataTable = "PROC_Name".SqlProcedureQuery(new {id = 1, age = 27}); ``` ```C# // ==== 异步操作 ==== // 示例一 var dataTable = await "PROC_Name".SqlProcedureQueryAsync(); // 示例二 var dataTable = await "PROC_Name".SqlProcedureQueryAsync(new {id = 1}); // 示例三 var dataTable = await "PROC_Name".SqlProcedureQueryAsync(new {id = 1, age = 27}); ``` -------------------------------- ### Implementing Pagination with ORM Source: https://help.zhouy1.com/furion/docs/sqlsugar-old Shows how to retrieve a paginated list of Student records, specifying page index, page size, and obtaining the total count. ```C# int pageIndex = 1; int pageSize = 20; int totalCount=0; var page = db.Queryable().ToPageList(pageIndex, pageSize, ref totalCount); ``` -------------------------------- ### Performing SQL Operations with ISqlRepository in Furion (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-sql The `ISqlRepository` interface provides a dedicated way to execute raw SQL operations without requiring entity mapping. This snippet shows examples of executing simple queries, parameterized queries, and mapping results to custom C# objects using `SqlQuery`. ```C# // 示例一 var dataTable = sqlRepository.SqlQuery("select * from person"); // 示例二 var dataTable = sqlRepository.SqlQuery("select * from person where id > @id", new { id = 10}); // 示例四 var persons = sqlRepository.SqlQuery("select * from person"); // 示例五 var persons = sqlRepository.SqlQuery("select * from person where id > @id", new { id = 10}); // 不再举例子。。。 ``` -------------------------------- ### Furion: Custom Route with HTTP GET Verb Source: https://help.zhouy1.com/furion/docs/dynamic-api-controller This C# example demonstrates defining a custom route for an action method while explicitly specifying the HTTP GET verb using `[HttpGet]`. This ensures the method only responds to GET requests at the defined custom path, combining routing with HTTP method constraints. ```C# using Furion.DynamicApiController; using Microsoft.AspNetCore.Mvc; namespace Furion.Application { [Route("api/[controller]")] public class FurionAppService : IDynamicApiController { [HttpGet("get/[action]")] public string GetVersion() { return "1.0.0"; } } } ``` -------------------------------- ### Manage Windows Services: Query, Start, Stop, Delete with sc.exe Source: https://help.zhouy1.com/furion/docs/process-service These shell commands provide essential operations for managing Windows Services via `sc.exe`. They cover querying service status, starting, stopping, and deleting services. All `sc.exe` commands for service management must be executed from an administrator-privileged console. ```Shell sc.exe query FurionWorkerServices sc.exe start FurionWorkerServices sc.exe stop NETCoreDemoWorkerService sc.exe delete NETCoreDemoWorkerService ``` -------------------------------- ### Furion: Setting URL Query Parameters Source: https://help.zhouy1.com/furion/docs/http This example demonstrates how to add query parameters to a URL. It supports both dictionary and anonymous object inputs for defining parameters, which are then automatically appended to the URL. ```C# // 字典方式 await "https://www.furion.icu/get".SetQueries(new Dictionary { { "id", 1 }, { "name", "Furion"} }); // 对象/匿名对象方式 await "https://www.furion.icu/get".SetQueries(new { id = 1, name = "Furion" }); ``` -------------------------------- ### jQuery $.ajax CORS Request Example Source: https://help.zhouy1.com/furion/docs/cors This JavaScript snippet provides an example of configuring a `$.ajax` request using jQuery to handle cross-origin communication. It explicitly sets `xhrFields.withCredentials` to `false` (or `true` for HTTPS) and `crossDomain` to `true`, which are common settings required for proper CORS behavior with jQuery. ```JavaScript $.ajax({ url: "http://localhost:8080/getdata", type: "GET", xhrFields: { withCredentials: false // 如果是https请求,可以试试 true }, crossDomain: true, success: function (res) { render(res); } }); ``` -------------------------------- ### Execute SQL Stored Procedure and Return Affected Rows Count in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Shows how to execute a SQL stored procedure using `SqlProcedureNonQuery` and `SqlProcedureNonQueryAsync` methods in C# to get the number of affected rows. Examples include passing an object or an anonymous type as parameters, for both synchronous and asynchronous operations. ```C# // ==== 同步操作 ==== // 示例一 var rowEffects = "PROC_Name".SqlProcedureNonQuery(person); // 示例二 var rowEffects = "PROC_Name".SqlProcedureNonQuery(new {id = 1, name = "新生帝", address ="广东省中山市"}); // 示例三 var rowEffects = "PROC_Name".SqlProcedureNonQuery(new {id=1, name="百小僧"}); // 示例四 var rowEffects = "PROC_Name".SqlProcedureNonQuery(new {id=1}); // ==== 异步操作 ==== // 示例一 var rowEffects = await "PROC_Name".SqlProcedureNonQueryAsync(person); // 示例二 var rowEffects = await "PROC_Name".SqlProcedureNonQueryAsync(new {id = 1, name = "新生帝", address ="广东省中山市"}); // 示例三 var rowEffects = await "PROC_Name".SqlProcedureNonQueryAsync(new {id=1, name="百小僧"}); // 示例四 var rowEffects = await "PROC_Name".SqlProcedureNonQueryAsync(new {id=1}); ``` -------------------------------- ### Call SQL Stored Procedure with OUTPUT and RETURN Parameters in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Demonstrates how to call a SQL stored procedure that uses output and return parameters, along with multiple result sets, using `SqlProcedureOutput` and `SqlProcedureOutputAsync` methods in C#. It shows examples of retrieving just output/return values or output/return values combined with multiple result sets. ```C# // ==== 同步操作 ==== // 示例一 ProcedureOutputResult result = "PROC_Name".SqlProcedureOutput(new ProcOutputModel{ Id=1}); // 示例二 ProcedureOutputResult result = "PROC_Name".SqlProcedureOutput(new ProcOutputModel{ Id=1}); // 示例三 ProcedureOutputResult<(List, List)> result = "PROC_Name".SqlProcedureOutput<(List, List)>(new ProcOutputModel{ Id=1}); // ==== 异步操作 ==== // 示例一 ProcedureOutputResult result = await "PROC_Name".SqlProcedureOutputAsync(new ProcOutputModel{ Id=1}); // 示例二 ProcedureOutputResult result = await "PROC_Name".SqlProcedureOutputAsync(new ProcOutputModel{ Id=1}); // 示例三 ProcedureOutputResult<(List, List)> result = await "PROC_Name".SqlProcedureOutputAsync<(List, List)>(new ProcOutputModel{ Id=1}); ``` -------------------------------- ### Execute SQL Non-Query and Get Affected Rows in C# Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Shows how to execute SQL commands (INSERT, UPDATE, DELETE) that do not return a result set, but instead return the number of rows affected. Examples cover various DML operations using synchronous `SqlNonQuery` and asynchronous `SqlNonQueryAsync` methods, with object and anonymous type parameters. ```C# // ==== 同步操作 ==== // 示例一 var rowEffects = "insert into person(Name,Age,Address) values(@name,@age,@address)".SqlNonQuery(person); // 示例二 var rowEffects = @" insert into person(Name,Age,Address) values(@name,@age,@address); insert into person(Name,Age,Address) values(@name,@age,@address);".SqlNonQuery(persons); // 示例三 var rowEffects = "update person set name=@name where id=@id".SqlNonQuery(new {id=1, name="百小僧"}); // 示例四 var rowEffects = "delete from person where @id > 10".SqlNonQuery(new {id=1}); ``` ```C# // ==== 异步操作 ==== // 示例一 var rowEffects = await "insert into person(Name,Age,Address) values(@name,@age,@address)".SqlNonQueryAsync(person); // 示例二 var rowEffects = @" insert into person(Name,Age,Address) values(@name,@age,@address); insert into person(Name,Age,Address) values(@name,@age,@address);".SqlNonQueryAsync(persons); // 示例三 var rowEffects = await "update person set name=@name where id=@id".SqlNonQueryAsync(new {id=1, name="百小僧"}); // 示例四 var rowEffects = await "delete from person where @id > 10".SqlNonQueryAsync(new {id=1}); ``` -------------------------------- ### Executing Raw SQL Queries and Stored Procedures Source: https://help.zhouy1.com/furion/docs/sqlsugar-old Illustrates how to execute raw SQL queries for pagination, retrieve DataTables with parameters (anonymous objects and SugarParameter list), and call stored procedures with input/output parameters. ```C# //sql分页 var list = db.SqlQueryable("select * from student").ToPageList(1, 2,ref total); //原生Sql用法 var dt=db.Ado.GetDataTable("select * from table where id=@id and name=@name",new List(){ new SugarParameter("@id",1), new SugarParameter("@name",2) }); //参数2 var dt=db.Ado.GetDataTable("select * from table where id=@id and name=@name",new{id=1,name=2}); //存储过程用法 var nameP= new SugarParameter("@name", "张三"); var ageP= new SugarParameter("@age", null, true);//设置为output var dt = db.Ado.UseStoredProcedure().GetDataTable("sp_school",nameP,ageP); ``` -------------------------------- ### Updating Data with ORM Source: https://help.zhouy1.com/furion/docs/sqlsugar-old Provides examples for updating single records by primary key, ignoring specific columns, updating only specified columns, and conditional updates based on expressions. ```C# //根据主键更新单条 参数 Class var result= db.Updateable(updateObj).ExecuteCommand(); //不更新 Name 和TestId var result=db.Updateable(updateObj).IgnoreColumns(it => new { it.CreateTime,it.TestId }).ExecuteCommand(); //只更新 Name 和 CreateTime var result=db.Updateable(updateObj).UpdateColumns(it => new { it.Name,it.CreateTime }).ExecuteCommand(); //根据表达式更新 var result71 = db.Updateable() .SetColumns(it => it.Name == "a") .SetColumnsIF(p!=null ,it => it.CreateTime == p.Value)//当p不等于null更新createtime列 .Where(it => it.Id == 11).ExecuteCommand(); ``` -------------------------------- ### Examples of Mixed Short and Long Parameters Source: https://help.zhouy1.com/furion/docs/dotnet-tools Shows how short and long parameters can be combined in a single command line, including special characters like slashes. In `-abc foo --hello world /new="slashes are ok too"`, 'a' and 'b' have no value, 'c' has value 'foo', 'hello' has value 'world', and 'new' has value 'slashes are ok too'. ```Shell -abc foo --hello world /new="slashes are ok too" ``` -------------------------------- ### Publish Custom Event Source in Furion Source: https://help.zhouy1.com/furion/docs/event-bus This snippet demonstrates how to publish an instance of a custom event source, `ToDoEventSource`, using the `_eventPublisher.PublishAsync` method. It shows a practical example of triggering an event with specific data. ```C# await _eventPublisher.PublishAsync(new ToDoEventSource ("ToDo:Create", "我的 ToDo Name")); ``` -------------------------------- ### Custom Advanced Dependency Injection Registration in C# Startup Source: https://help.zhouy1.com/furion/docs/dependency-injection This C# code snippet illustrates how to perform custom, advanced dependency injection registration within the `Startup` class using `services.AddScoped`. It allows developers to define any custom instance creation logic, such as returning a new instance or a proxy instance, for specific services. ```C# services.AddScoped(typeof(ISpecService), provider = > { // 自定义任何创建实例的方式 var instance = new SpecService(); // 或者可以通过 AOP插件返回代理实例 return instance; }); ``` -------------------------------- ### Generated SQL for SqlSugar Dynamic Expression Source: https://help.zhouy1.com/furion/docs/sqlsugar This SQL snippet shows the database query generated by SqlSugar for the dynamic expression example. It illustrates how the `Expressionable` translates into a `WHERE` clause with multiple `LIKE` conditions combined by `OR` operators. ```SQL SELECT [Id],[Name],[Price],[CreateTime],[CustomId] FROM [Order] WHERE ( ([Name] like '%'+ CAST(@MethodConst0 AS NVARCHAR(MAX))+'%') OR ([Name] like '%'+ CAST(@MethodConst1 AS NVARCHAR(MAX))+'%') ) ``` -------------------------------- ### Navigate to Migrations Project Directory (CLI) Source: https://help.zhouy1.com/furion/docs/dbcontext-code-first Navigates the command line into the `Furion.Database.Migrations` project directory. This step is necessary before executing `dotnet ef` commands, as they typically operate relative to the project containing the migration files. ```CLI cd Furion.Database.Migrations ``` -------------------------------- ### Inserting Data with ORM Source: https://help.zhouy1.com/furion/docs/sqlsugar-old Covers various methods for inserting data, including inserting objects, returning identity columns, inserting from dictionaries, and DataTable, along with an example of entity configuration for primary keys and identity columns. ```C# //可以是 类 或者 List<类> db.Insertable(insertObj).ExecuteCommand(); //插入返回自增列 db.Insertable(insertObj).ExecuteReturnIdentity(); //可以是 Dictionary 或者 List var dc= new Dictionary(); dt.Add("name", "1"); dt.Add("CreateTime", null); db.Insertable(dc).AS("student").ExecuteCommand(); //DataTable插入 Dictionary dc= db.Utilities.DataTableToDictionary(dataTable);//转成字典就可以按上面的字典更新了 db.Insertable(dc).AS("student").ExecuteReturnIdentity(); //实体可以配置主键和自增列 public class Student { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int Id { get; set; } public int? SchoolId { get; set; } public string Name { get; set; } } ``` -------------------------------- ### Perform Fuzzy String Search in Furion ORM (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-query Demonstrates how to perform fuzzy string matching queries (like, starts with, ends with, contains) on string properties using the Furion ORM. Examples include `StartsWith`, `EndsWith`, and `Contains` methods. ```C# // 示例一 repository.Where(u => u.Name.StartsWith("Furion")); // 示例二 _testRepository.Where(u => u.Name.EndsWith("Furion")); // 示例三 _testRepository.Where(u => u.Name.Contains("Furion")); ``` -------------------------------- ### Perform Date Range Query in Furion ORM (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-query Shows how to filter records based on a date range using the Furion ORM. The example demonstrates querying records where a `CreatedDt` property falls within a specified start and end date. ```C# var starDate = DateTime.Parse("2020-09-10"); var endDate = DateTime.Parse("2020-09-10"); var query = repository.Where(u => u.CreatedDt >= starDate && u.CreatedDt <= endDate); ``` -------------------------------- ### Examples of Long Parameters in .NET Tools Source: https://help.zhouy1.com/furion/docs/dotnet-tools Demonstrates the usage and parsing of long parameters, showing how values are associated and how multiple long parameters are handled. For `--foo bar`, 'foo' has value 'bar'. For `--foo --bar`, 'foo' and 'bar' have no value. For `--foo bar --hello world`, 'foo' has value 'bar' and 'hello' has value 'world'. ```Shell --foo bar ``` ```Shell --foo --bar ``` ```Shell --foo bar --hello world ``` -------------------------------- ### Generated SQL for SqlSugar Join Query Source: https://help.zhouy1.com/furion/docs/sqlsugar This SQL snippet shows the database query generated by SqlSugar for the Linq/Lambda join example. It illustrates the `SELECT`, `FROM`, `LEFT JOIN`, and `WHERE` clauses, demonstrating how the ORM translates the C# expression into a native SQL statement. ```SQL SELECT [o].[Id] AS [Id], [cus].[Name] AS [CustomName] FROM [Order] o Left JOIN [Custom] cus ON ([o].[CustomId] = [cus].[Id]) Left JOIN [OrderDetail] oritem ON ([o].[Id] = [oritem].[OrderId]) WHERE ([o].[Id] = @Id0) ``` -------------------------------- ### Register Multi-Tenant DbContexts in Furion Startup (C#) Source: https://help.zhouy1.com/furion/docs/saas This C# code demonstrates how to register multiple database contexts, including a multi-tenant specific context (`MultiTenantDbContext`), using Furion's `AddDatabaseAccessor` method within the `ConfigureServices` method of an `AppStartup` class. This ensures the contexts are properly configured for dependency injection. ```C# using Furion.DatabaseAccessor; using Microsoft.Extensions.DependencyInjection; namespace Furion.EntityFramework.Core { [AppStartup(600)] public sealed class FurEntityFrameworkCoreStartup : AppStartup { public void ConfigureServices(IServiceCollection services) { services.AddDatabaseAccessor(options => { options.AddDbPool(); options.AddDbPool(); }); } } } ``` -------------------------------- ### Overriding Default HTTP Method Mapping in Furion Source: https://help.zhouy1.com/furion/docs/dynamic-api-controller This JSON configuration snippet demonstrates how to override the default `VerbToHttpMethods` rules within `DynamicApiControllerSettings` in Furion. It shows an example of mapping 'getall' to `[HttpHead]` and adding a new rule to map methods starting with 'other' to `[HttpPut]`. ```JSON "DynamicApiControllerSettings": { "VerbToHttpMethods": [ [ "getall", "HEAD" ], // => getall 会被复写为 `[HttpHead]` [ "other", "PUT" ] // => 新增一条新规则,比如,一 `[other]` 开头会转换为 `[HttpPut]` 请求 ] } ``` -------------------------------- ### Enable Serilog Request Logging Middleware in Startup.cs Source: https://help.zhouy1.com/furion/docs/logging Explains how to enable Serilog's request logging middleware in the Configure method of Startup.cs. It highlights the importance of placing UseSerilogRequestLogging() between UseStaticFiles() and UseRouting() for proper functionality. ```C# public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseStaticFiles(); app.UseSerilogRequestLogging(); // 必须在 UseStaticFiles 和 UseRouting 之间 app.UseRouting(); } ``` -------------------------------- ### Implement Custom Event Handler Executor for Retries Source: https://help.zhouy1.com/furion/docs/event-bus This C# class, `RetryEventHandlerExecutor`, implements the `IEventHandlerExecutor` interface to define a custom execution strategy for event handlers. This example demonstrates implementing a retry mechanism, attempting to re-execute the handler up to three times with a 1-second delay on failure. ```C# public class RetryEventHandlerExecutor : IEventHandlerExecutor { public async Task ExecuteAsync(EventHandlerExecutingContext context, Func handler) { // 如果执行失败,每隔 1s 重试,最多三次 await Retry(async () => { await handler(context); }, 3, 1000); } } ``` -------------------------------- ### Defining a Custom SqlSugar Repository Class Source: https://help.zhouy1.com/furion/docs/sqlsugar This C# code defines a generic `Repository` class that extends SqlSugar's `SimpleClient`. It provides a constructor to initialize the context, ensuring that the repository can utilize the `ISqlSugarClient` instance, potentially supporting repository switching. ```C# public class Repository : SimpleClient where T : class, new() { public Repository(ISqlSugarClient context = null) : base(context)//默认值等于null不能少 { base.Context = App.GetService();//用手动获取方式支持切换仓储 } } ``` -------------------------------- ### Example Furion MVC Controller with Dynamic API Support Source: https://help.zhouy1.com/furion/docs/dynamic-api-controller This C# code defines a simple `MvcController` inheriting from `ControllerBase`. When `SupportedMvcController` is enabled in Furion's settings, this controller will automatically gain dynamic Web API capabilities, allowing its `Get` method to be exposed as an API endpoint. ```C# using Microsoft.AspNetCore.Mvc; namespace Furion.Web.Entry.Controllers { public class MvcController : ControllerBase { public string Get() { return nameof(Furion); } } } ``` -------------------------------- ### Automate Database Creation on Application Startup (C#) Source: https://help.zhouy1.com/furion/docs/dbcontext-code-first Configures the application to automatically create the database if it doesn't exist when the application starts, specifically in a development environment. It retrieves the `FurionDbContext` and calls `context.Database.EnsureCreated()` to ensure the database and schema are created based on the model, useful when no migrations exist. ```C# public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // 判断开发环境!!!必须!!!! if (env.IsDevelopment()) { Scoped.Create((_, scope) => { var context = scope.ServiceProvider.GetRequiredService(); context.Database.EnsureCreated(); }); } // 其他代码 } ``` -------------------------------- ### Dynamically Get Connection String in Furion Source: https://help.zhouy1.com/furion/docs/dbcontext This example demonstrates how to use the `DbProvider.GetConnectionString` static method in Furion to dynamically retrieve a connection string for a `DbContext`. This method automatically reads configuration based on the context name and can be used to provide connection strings for custom database configurations. ```C# // 获取连接字符串 var connStr = DbProvider.GetConnectionString(/*这里可写可不写*/); options.AddDb(builder => { builder.UseSqlite(connStr, ...); }); ``` -------------------------------- ### Define SQL Stored Procedure with OUTPUT and RETURN Parameters Source: https://help.zhouy1.com/furion/docs/dbcontext-sql Defines a SQL stored procedure `PROC_Output` that demonstrates the use of input, output, and return parameters. It also shows how to return multiple result sets from a single procedure. ```SQL CREATE PROC PROC_Output @Id INT, // 输入参数 @Name NVARCHAR(32) OUTPUT, // 输出参数,还带长度 @Age INT OUTPUT // 输出参数 AS BEGIN SET @Name = 'Furion Output'; // 输出结果集 SELECT * FROM dbo.Test WHERE Id > @Id; // 输出结果集 SELECT TOP 10 * FROM dbo.Test; SET @Age = 27; // 带 RETURN 返回 RETURN 10; END; ``` -------------------------------- ### SqlSugar Join Query using Linq/Lambda Source: https://help.zhouy1.com/furion/docs/sqlsugar This C# example demonstrates how to perform a multi-table join query using SqlSugar's Linq/Lambda syntax. It performs a `LeftJoin` between `Order`, `Custom`, and `OrderItem` tables, filters by `OrderId`, and selects specific columns into a `ViewOrder` DTO. ```C# var query5 = db.Queryable() .LeftJoin ((o, cus) => o.CustomId == cus.Id) .LeftJoin ((o, cus, oritem ) => o.Id == oritem.OrderId) .Where(o => o.Id == 1) .Select((o, cus) => new ViewOrder { Id = o.Id, CustomName = cus.Name }) .ToList(); ``` -------------------------------- ### Furion Framework - Lazy Mode Logging with String Extensions Source: https://help.zhouy1.com/furion/docs/logging Demonstrates a simplified way to write logs in the Furion framework using string extension methods like LogInformation(), LogError(), and SetCategory(). This allows for quick and convenient logging anywhere in the application. ```C# "简单日志".LogInformation(); "百小僧 新增了一条记录".LogInformation(); "程序出现异常啦".LogError(); "这是自定义类别日志".SetCategory("类别").LogInformation(); ```