Updated Repository Layer (markdown)

2881099
2024-01-29 09:02:05 +08:00
parent 51cdf8aa23
commit ab715c01c1

@@ -119,6 +119,51 @@ repo.CompareState(item) can obtain the status change information
Dictionary<string, object[]> 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<User>();
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<TEntity, TKey> : BaseRepository<TEntity, TKey> 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<TEntity> : MyRepository<TEntity, long> where TEntity : class
{
public MyRepository(IFreeSql fsql, MyRepositoryOptions options) : base(fsql, options) { }
}
class MyRepositoryOptions
{
public Action<DbContextAuditValueEventArgs> AuditValue { get; set; }
}
```
## Filtering and Verification
Suppose we have two entities: `User` and `Topic`, and two repositories are defined in the domain class: