### Quick Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据模拟压测(DataSimulation).md A quick example demonstrating how to use DataSimulation to run a load test and print the TPS. ```csharp var sim = new DataSimulation { Threads = Environment.ProcessorCount, BatchSize = 2000, UseSql = false, Log = XTrace.Log }; sim.Run(100_000); Console.WriteLine($"TPS={sim.Score:n0}"); ``` -------------------------------- ### Multi-role Permission Merging Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据权限.md Example demonstrating how permissions are merged when a user has multiple roles. ```csharp // 假设用户有两个角色: // 角色A:DataScope = 仅本人 (3) // 角色B:DataScope = 本部门及下级 (1) // 最终权限 = Min(3, 1) = 本部门及下级 ``` -------------------------------- ### Dynamic Database Sharding Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode数据模型与结构同步.md C# code example showing how to select a database shard based on a user ID and then switch the connection. ```csharp // 根据用户 ID 选择分库 var shardIndex = userId % 4; var connName = $"Shard_{shardIndex:D2}"; // Shard_00 ~ Shard_03 // 切换连接 User.Meta.ConnName = connName; ``` -------------------------------- ### Typical Usage Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/字段缓存FieldCache.md Example demonstrating how to initialize and use FieldCache to get a dictionary of field values and their counts. ```csharp var fc = new FieldCache("RoleID") { MaxRows = 20, GetDisplay = e => e["RoleName"] + "", }; var dic = fc.FindAllName(); // 结果:{"1":"管理员 (120)", "2":"访客 (56)"} ``` -------------------------------- ### Entity Metadata Examples Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md C# code examples demonstrating how to access entity metadata such as type, table information, fields, and session. ```csharp // Get entity type var type = User.Meta.ThisType; // Get table information var table = User.Meta.Table; var tableName = User.Meta.TableName; var connName = User.Meta.ConnName; // Get field information var fields = User.Meta.Fields; var allFields = User.Meta.AllFields; var unique = User.Meta.Unique; var master = User.Meta.Master; // Get session var session = User.Meta.Session; var count = User.Meta.Count; ``` -------------------------------- ### Soft Delete Persistence Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体持久化接口与默认实现(IEntityPersistence).md Example of a custom persistence implementation for soft deletion. ```csharp public class SoftDeletePersistence : EntityPersistence { public SoftDeletePersistence(IEntityFactory factory) : base(factory) { } public override Int32 Delete(IEntitySession session, IEntity entity) { // 软删除:改状态字段,不做物理删除 return Update(session, new[] { "IsDeleted", "UpdateTime" }, new Object[] { true, DateTime.Now }, new[] { "Id" }, new Object[] { entity["Id"]! }); } } ``` -------------------------------- ### Dynamic Table Sharding Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode数据模型与结构同步.md C# code example demonstrating how to dynamically set a table name based on the current month for monthly sharding and ensuring the table exists using the migration mode. ```csharp // 按月分表 var tableName = $"Log_{DateTime.Now:yyyyMM}"; // Log_202602 // 修改 IDataTable var dt = TableItem.Create(typeof(Log)).DataTable; dt.TableName = tableName; // 确保表存在 DAL.Create("Main").SetTables(Migration.OnlyCreate, dt); ``` -------------------------------- ### UserBehaviorMiddleware Core Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/ASP.NET Core行为监测迁移指南.md A simplified C# example of the UserBehaviorMiddleware for ASP.NET Core, demonstrating how to capture request timing, SQL counts, and user behavior data. ```csharp public class UserBehaviorMiddleware { private readonly RequestDelegate _next; public UserBehaviorMiddleware(RequestDelegate next) => _next = next; public async Task Invoke(HttpContext ctx) { var begin = DateTime.Now; var q1 = DAL.QueryTimes; var e1 = DAL.ExecuteTimes; Exception? ex = null; try { await _next(ctx).ConfigureAwait(false); } catch (Exception err) { ex = err; throw; } finally { var cost = (Int32)(DateTime.Now - begin).TotalMilliseconds; var page = NormalizePath(ctx.Request.Path); var ip = GetIP(ctx); var user = ctx.User?.Identity?.Name; var model = new VisitStatModel { Time = DateTime.Now, Page = page, Title = page, Cost = cost, User = user, IP = ip, Error = ex?.Message }; VisitStat.Process(model, StatLevels.Day, StatLevels.Month, StatLevels.Year); var q = DAL.QueryTimes - q1; var c = DAL.ExecuteTimes - e1; ctx.Response.Headers["X-DbRuntime"] = $"Q={q};E={c};Cost={cost}ms"; } } private static String NormalizePath(PathString path) { var p = path.Value + ""; return p; } private static String GetIP(HttpContext ctx) { var ip = ctx.Request.Headers["X-Forwarded-For"].FirstOrDefault(); if (ip.IsNullOrEmpty()) ip = ctx.Request.Headers["X-Real-IP"].FirstOrDefault(); if (ip.IsNullOrEmpty()) ip = ctx.Connection.RemoteIpAddress + ""; return ip + ""; } } ``` -------------------------------- ### Install NewLife.Templates and create a new project Source: https://github.com/newlifex/newlife.xcode/blob/master/Readme.MD Install NewLife.Templates and create a new project using the xcode template. ```bash dotnet new install NewLife.Templates dotnet new xcode --name Demo.Data cd Demo.Data dotnet build ``` -------------------------------- ### Typical Usage Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/配置中心DbConfigProvider.md Example demonstrating how to initialize and use DbConfigProvider. ```csharp var provider = new DbConfigProvider { UserId = 0, Category = "MyApp", CacheLevel = ConfigCacheLevel.Json, Period = 15, }; Config.SetProvider(provider); provider.LoadAll(); provider.Bind(MySetting.Current, autoReload: true); ``` -------------------------------- ### Quick Time Period Methods - Day Examples Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/字段时间区间扩展(FieldExtension).md Examples of using quick time period methods for days, such as Today() and LastDays(n). ```csharp Order.FindAll(_.CreateTime.Today()) // Orders today Order.FindAll(_.CreateTime.LastDays(7)) // Last 7 days ``` -------------------------------- ### Line Protocol Format Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/InfluxDB支持说明.md Examples demonstrating the Line Protocol format for writing data. ```csharp // Basic example "temperature value=23.5" // With tags "temperature,location=room1,sensor=sensor1 value=23.5" // Multiple fields "temperature,location=room1 value=23.5,humidity=45" // With timestamp (nanoseconds) var nanos = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 1000000; $"temperature,location=room1 value=23.5 {nanos}" ``` -------------------------------- ### Registering UserInterceptor Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体拦截器(IEntityInterceptor).md Example of registering the UserInterceptor. ```csharp Meta.Modules.Add(); ``` -------------------------------- ### Registering IPInterceptor Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体拦截器(IEntityInterceptor).md Example of registering the IPInterceptor. ```csharp Meta.Modules.Add(); ``` -------------------------------- ### Flux Query Language Examples Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/InfluxDB支持说明.md Examples of Flux queries for different data retrieval scenarios. ```csharp // 1. Query data from the last 1 hour var flux = @" from(bucket: \"my-bucket\") |> range(start: -1h) "; // 2. Filter by measurement var flux = @" from(bucket: \"my-bucket\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"temperature\") "; // 3. Filter by tag var flux = @" from(bucket: \"my-bucket\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"temperature\") |> filter(fn: (r) => r.location == \"room1\") "; // 4. Aggregation query (average) var flux = @" from(bucket: \"my-bucket\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"temperature\") |> aggregateWindow(every: 5m, fn: mean) "; // 5. Limit the number of results var flux = @" from(bucket: \"my-bucket\") |> range(start: -1h) |> limit(n: 100) "; ``` -------------------------------- ### Manual Module Upgrade Example Source: https://github.com/newlifex/newlife.xcode/blob/master/XCode/Code/EntityBuilder模块名称升级说明.md Example of manually configuring EntityBuilder for module upgrades. ```csharp var builder = new EntityBuilder { AllTables = tables, Option = option, Log = log, EnableUpgradeModuleNames = true // 手动开启升级 }; builder.Load(table); builder.Business = true; builder.Execute(); builder.Save(null, false, chineseFileName); ``` -------------------------------- ### Registering TraceInterceptor Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体拦截器(IEntityInterceptor).md Example of registering the TraceInterceptor. ```csharp Meta.Modules.Add(); ``` -------------------------------- ### Entity Class Operations: Query Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md Examples of querying entity objects. ```csharp // 按主键查询 var user = User.FindByKey(1); var user = User.FindByKey(1, "Id,Name"); // 指定返回字段 // 按条件查询单个 var user = User.Find(User._.Name == "test"); var user = User.Find(User._.Status == 1 & User._.Enable == true); // 查询列表 var list = User.FindAll(); var list = User.FindAll(User._.Status == 1); var list = User.FindAll(User._.Status == 1, User._.Id.Desc(), null, 0, 10); // 异步查询 var user = await User.FindAsync(User._.Id == 1); var list = await User.FindAllAsync(User._.Status == 1); ``` -------------------------------- ### 插入处理模块 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/ETL数据转换.md Example of inserting a custom processing module into the ETL pipeline. ```csharp etl.Module = new MyFilterModule(); ``` -------------------------------- ### Supported csproj Formats Source: https://github.com/newlifex/newlife.xcode/blob/master/XCode/Code/EntityBuilder模块名称升级说明.md Examples of supported csproj formats for PackageReference. ```xml 11.23.2026.127-beta0417 ``` -------------------------------- ### Create Model (db.xml) Source: https://github.com/newlifex/newlife.xcode/blob/master/Readme.MD Example of creating a model definition in db.xml. ```xml
``` -------------------------------- ### 统计信息访问 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/ETL数据转换.md Example of accessing the statistics object to get processing counts. ```csharp var stat = etl.Stat; Console.WriteLine($"成功={{stat.Success}} 错误={{stat.Error}}"); ``` -------------------------------- ### Scenario 3: Single Tenant Deployment (Startup Configuration) Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/TableItem启动配置.md Configuration example for permanently specifying the tenant database connection during startup for a single-tenant deployment. ```csharp public class SingleTenantConfig { public static void Configure(String tenantId) { // 整个应用只服务一个租户,启动时永久指定租户数据库 var connName = $"Tenant_{tenantId}"; User.Meta.Table.ConnName = connName; Order.Meta.Table.ConnName = connName; Product.Meta.Table.ConnName = connName; DAL.WriteLog("已为单租户 {0} 配置数据库连接:{1}", tenantId, connName); } } ``` -------------------------------- ### Read-Only (No Refresh) Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体扩展字典(EntityExtend).md Example of getting a cached value without triggering a refresh if it doesn't exist. ```csharp // 不传 func,只读当前缓存值,不存在时返回 null var cached = Extends.Get(nameof(RoleName)); ``` -------------------------------- ### Common Access Methods Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/脏数据跟踪机制(DirtyCollection).md Examples of how to check if a field is dirty, enumerate dirty fields, and get a dictionary of old values. ```csharp // 判断字段是否为脏 var changed = entity.Dirtys[User._.RoleId.Name]; // 枚举所有脏字段 foreach (var name in entity.Dirtys) { Console.WriteLine(name); } // 获取字段旧值字典 var olds = entity.Dirtys.GetDictionary(); ``` -------------------------------- ### Scenario 2: Sharding Strategy (Startup Configuration) Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/TableItem启动配置.md Configuration example for distributing tables to different databases based on business modules during startup. ```csharp public class ShardingConfig { public static void Configure() { // 按业务模块分配到不同数据库 User.Meta.Table.ConnName = "UserDB"; Order.Meta.Table.ConnName = "OrderDB"; Product.Meta.Table.ConnName = "ProductDB"; Log.Meta.Table.ConnName = "LogDB"; DAL.WriteLog("已配置分库策略"); } } ``` -------------------------------- ### Scenario 1: Table Prefix Scene (Startup Configuration) Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/TableItem启动配置.md Configuration example for applying a uniform prefix to all table names during startup. ```csharp public class TablePrefixConfig { public static void Configure(String prefix) { // 为所有表添加统一前缀 User.Meta.Table.TableName = $"{prefix}_{User.Meta.TableName}"; Order.Meta.Table.TableName = $"{prefix}_{Order.Meta.TableName}"; Product.Meta.Table.TableName = $"{prefix}_{Product.Meta.TableName}"; DAL.WriteLog("已为所有表配置前缀:{0}", prefix); } } ``` -------------------------------- ### Install Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/InfluxDB支持说明.md Install the NewLife.XCode package using the .NET CLI. ```bash dotnet add package NewLife.XCode ``` -------------------------------- ### ShowIn Syntax Examples Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/字段元数据FieldItem与ShowIn.md Demonstrates the three supported syntaxes for configuring ShowIn options: named lists, pipe-separated segments, and character masks. ```csharp 1. 具名列表(推荐) - `ShowIn="List,Search"` - `ShowIn="All,-Detail"` 2. 管道五段 - `ShowIn="Y|Y|N||A"` 3. 五字符掩码 - `ShowIn="10A?-"` ``` -------------------------------- ### Entity Model Definition Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md An example of an entity model definition in XML format. ```xml
``` -------------------------------- ### CRUD Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Readme.MD Example of performing CRUD operations using the generated UserInfo entity. ```csharp using XCode; var user = new UserInfo { UserName="张三", Password="123456", Age=18 }; user.Insert(); var u2 = UserInfo.FindById(user.Id); u2.Age = 19; u2.Update(); var list = UserInfo.FindAll(UserInfo._.Age > 10 & UserInfo._.UserName == "张三"); UserInfo.FindById(user.Id)?.Delete(); ``` -------------------------------- ### Typical Usage Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/单对象缓存SingleCache.md Demonstrates how to read from the cache using the primary key and a slave key. ```csharp // 主键读 var user = User.Meta.SingleCache[1001]; // 从键读(例如用户名) var user2 = User.Meta.SingleCache.GetItemWithSlaveKey("admin"); ``` -------------------------------- ### Automatic Module Upgrade Example Source: https://github.com/newlifex/newlife.xcode/blob/master/XCode/Code/EntityBuilder模块名称升级说明.md Example of how to automatically upgrade XCode versions when calling EntityBuilder.BuildTables(). ```csharp // 自动检测 XCode 版本并执行升级 EntityBuilder.BuildTables(tables, option, log); ``` -------------------------------- ### TimeShardPolicy Configuration Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/时间分片策略与范围裁剪(TimeShardPolicy).md Example of configuring TimeShardPolicy with specific connection and table policies, and a daily step. ```csharp Meta.ShardPolicy = new TimeShardPolicy(nameof(CreateTime), Meta.Factory) { ConnPolicy = "{0}", TablePolicy = "{0}_{1:yyyyMM}", Step = TimeSpan.FromDays(1) }; ``` -------------------------------- ### Path Query Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/树形实体.md Shows how to find a node by its path and how to retrieve the full path string of a node. ```csharp // 按路径查找节点,路径格式:中国/广东/广州 var node = Area.FindByPath("中国/广东/广州"); // 获取完整路径字符串(默认分隔符 /) var path = node.GetFullPath(); // 中国/广东/广州 var path2 = node.GetFullPath(false); // 中国/广东(不含自身) ``` -------------------------------- ### EntitySplit Usage Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/分库分表临时切换(EntitySplit).md An example demonstrating how to use EntitySplit to temporarily switch the database and table for a specific operation. ```csharp factory.Split("Db_202603", "Log_202603", () => { return Log.FindCount(); }); ``` -------------------------------- ### 辅助功能 - 临时改变 ShowSQL Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据库会话接口(IDbSession).md 使用 using 语句临时改变 ShowSQL 选项,并在离开作用域时自动还原。 ```csharp // 临时改变 ShowSQL 并自动还原 using var _ = session.SetShowSql(true); ``` -------------------------------- ### External Version Detection Example Source: https://github.com/newlifex/newlife.xcode/blob/master/XCode/Code/EntityBuilder模块名称升级说明.md Example of detecting XCode version using external tools like xcodetool. ```csharp // 检测当前目录的 XCode 版本 var version = EntityBuilder.DetectXCodeVersion(Environment.CurrentDirectory); if (EntityBuilder.NeedUpgradeModuleNames(version)) { Console.WriteLine($"当前 XCode 版本 {version} 需要升级模块名称"); } ``` -------------------------------- ### Usage Example in MySQL Driver Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/驱动自动加载与下载(DriverLoader).md Demonstrates how the `CreateFactory` method in a database driver (specifically MySQL) uses `DriverLoader.Load` to obtain the necessary `DbProviderFactory`. ```csharp // MySQL driver example protected override DbProviderFactory? CreateFactory() { return DriverLoader.Load( "MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data", "MySql", "MySql.Data.dll", "MySql.Data", null, new Version("8.0") ) as DbProviderFactory; } ``` -------------------------------- ### Quick Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/连接字符串构造与脱敏处理(ConnectionStringBuilder).md Demonstrates basic usage of ConnectionStringBuilder for modifying database, adding pooling, and handling password removal. ```csharp var b = new ConnectionStringBuilder("Server=127.0.0.1;Database=Test;User=sa;Password=123456"); b["Database"] = "Prod"; b.TryAdd("Pooling", "true"); if (b.TryGetAndRemove("Password", out var pwd)) { // 可在这里做脱敏日志或密钥托管 } var conn = b.ConnectionString; ``` -------------------------------- ### Query Combination Example - This Month + Status Filter Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/字段时间区间扩展(FieldExtension).md Example demonstrating how to combine a time period filter (ThisMonth) with a status filter. ```csharp // This month + status filter var list = Order.FindAll( _.CreateTime.ThisMonth() & _.Status == 1, _.Id.Desc(), null, 0, 20 ); ``` -------------------------------- ### Query Combination Example - Custom Range + User Filter Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/字段时间区间扩展(FieldExtension).md Example showing how to combine a custom date range with a user ID filter. ```csharp var exp = _.CreateTime.Between(startDate, endDate) & _.UserId == userId; ``` -------------------------------- ### 自动填充用户信息 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/业务审计日志(LogProvider).md CreateLog 内部会调用,无需手动传入用户,Cube 环境下自动来自当前请求上下文。 ```csharp var user = ManageProvider.Provider?.Current; if (user != null) { log.CreateUserID = user.ID; log.UserName = user.ToString(); } log.CreateIP = ManageProvider.UserHost; ``` -------------------------------- ### 设置数据权限上下文 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据权限.md 在请求开始时设置当前用户的数据权限上下文。 ```csharp // ASP.NET Core 中间件示例 public class DataScopeMiddleware { public async Task InvokeAsync(HttpContext context, IManageProvider provider) { var user = provider.Current as IUser; if (user != null) { // 从用户创建数据权限上下文 DataScopeContext.Current = DataScopeContext.Create(user); } try { await _next(context); } finally { DataScopeContext.Current = null; } } } ``` -------------------------------- ### Enable 开关 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/业务审计日志(LogProvider).md 全局禁用日志记录,适用于压测/迁移场景。 ```csharp // 全局禁用(如压测/迁移场景) LogProvider.Provider.Enable = false; ``` -------------------------------- ### BindIndexAttribute Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体绑定特性(Attributes).md 标注在实体类上(可多次),声明数据表索引。 ```csharp [BindIndex("IU_User_Name", true, "Name")] [BindIndex("IX_User_RoleId", false, "RoleId")] public partial class User : Entity { } ``` -------------------------------- ### 创建项目 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md 创建数据类库项目、Web 管理后台和控制台应用的命令。 ```powershell # 创建数据类库项目 dotnet new xcode -n MyApp.Data # 创建 Web 管理后台 dotnet new cube -n MyAppWeb # 创建控制台应用 dotnet new nconsole -n MyAppConsole ``` -------------------------------- ### 基本用法 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据初始化(InitData).md 在业务类(xxx.Biz.cs)中重写 InitData() 方法,用于在实体第一次初始化时插入默认数据。示例展示了如何插入角色信息,并包含了一个检查以防止重复写入。 ```csharp public partial class Role : Entity { protected override void InitData() { if (Meta.Count > 0) return; // 已有数据则不重复写入 var roles = new[] { new Role { Name = "管理员", Enable = true, IsSystem = true, Sort = 1 }, new Role { Name = "普通用户", Enable = true, Sort = 2 }, }; roles.Insert(); // 批量插入 } } ``` -------------------------------- ### BindColumnAttribute Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体绑定特性(Attributes).md 标注在实体属性上,声明该属性对应的数据列。 ```csharp [BindColumn("UserName", "用户名。登录账号", "", Master = true)] public String? UserName { get; set; } [BindColumn("LastLoginIP", "最后登录IP", "varchar(50)", ShowIn = "-EditForm,-AddForm")] public String? LastLoginIP { get; set; } ``` -------------------------------- ### BindTableAttribute Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体绑定特性(Attributes).md 标注在实体类上,声明该类对应的数据表。 ```csharp [BindTable("User", Description = "用户。系统管理用户", ConnName = "Sys", DbType = DatabaseType.None)] public partial class User : Entity { } ``` -------------------------------- ### 菜单级数据权限设置示例 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据权限.md 展示了如何通过 DataScopeContext.Create 或 DataScopeContext.Current.SetMenu 来设置当前菜单的数据权限。 ```csharp // 设置当前菜单 var ctx = DataScopeContext.Create(user, menuId: 100); // 或者动态设置 DataScopeContext.Current?.SetMenu(menuId); ``` -------------------------------- ### MapAttribute Example Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体绑定特性(Attributes).md 标注在外键属性上(如 RoleId),声明关联实体的映射关系,用于自动提供下拉数据源与扩展属性。 ```csharp [Map(nameof(RoleId), typeof(Role), "Id")] public Int32 RoleId { get; set; } ``` -------------------------------- ### Creating a DataScopeContext Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/数据权限.md Recommended way to create a DataScopeContext from a user object. ```csharp // 从用户创建上下文 var ctx = DataScopeContext.Create(user); // 也可以指定菜单,实现菜单级数据权限 var ctx = DataScopeContext.Create(user, menuId: 100); ``` -------------------------------- ### using 方式事务处理 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md 演示推荐的 using 方式进行事务处理。 ```csharp using var tran = User.Meta.CreateTrans(); var user = new User { Name = "test" }; user.Insert(); var log = new Log { Action = "新增用户" }; log.Insert(); tran.Commit(); // 不调用则自动回滚 ``` -------------------------------- ### Registering TimeInterceptor Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体拦截器(IEntityInterceptor).md Example of registering the TimeInterceptor in the static constructor of an entity. ```csharp static MyEntity() { // 推荐新写法 Meta.Modules.Add(); // 旧写法(仍可用,内部等价) Meta.Modules.Add(); } ``` -------------------------------- ### Clear Cache Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/实体扩展字典(EntityExtend).md Example of clearing all extended property caches for an entity. ```csharp entity.Extends.Clear(); // 清空该实体的全部扩展属性缓存 ``` -------------------------------- ### 配置数据库连接 Source: https://github.com/newlifex/newlife.xcode/blob/master/Doc/XCode使用手册.md 在 appsettings.json 文件中配置数据库连接的 JSON 示例。 ```json { "ConnectionStrings": { "Default": "Server=.;Database=MyApp;Uid=sa;Pwd=xxx" } } ```