From ab715c01c1d9ddddae24fd8a9bfcd971ec51243f Mon Sep 17 00:00:00 2001 From: 2881099 <2881099@users.noreply.github.com> Date: Mon, 29 Jan 2024 09:02:05 +0800 Subject: [PATCH] Updated Repository Layer (markdown) --- Repository-Layer.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Repository-Layer.md b/Repository-Layer.md index 2e85ef2..0e4fc6c 100644 --- a/Repository-Layer.md +++ b/Repository-Layer.md @@ -119,6 +119,51 @@ repo.CompareState(item) can obtain the status change information Dictionary CompareState(TEntity newdata); ``` +## Ioc + Login + +`repo.DbContextOptions.AuditValue` is suitable for combining with Ioc AddScoped information. + +Example: Automatically use login information when using warehouse insert/update + +```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; } +} +``` + ## Filtering and Verification Suppose we have two entities: `User` and `Topic`, and two repositories are defined in the domain class: