Ef Core花里胡哨系列(5) 動態(tài)修改追蹤的實體、動態(tài)查詢
同樣還是IModelCacheKeyFactory
,不過這次要采用主動刷新的方式。
實現(xiàn)DbContext
動態(tài)實體,根據(jù)配置等生成動態(tài)類型來當作數(shù)據(jù)庫實體使用,當配置修改時,可以調(diào)用DynamicModelCacheKeyFactory.Refresh()
刷新DbContext。
動態(tài)構(gòu)建部分不提供,我們將在其它的地方進行討論。
public class SampleDbContext(DbContextOptions<SampleDbContext> options)
: DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 構(gòu)建所有的FormType
FormTypeBuilderService.BuildFormTypes();
// 將Type添加到DbContext上下文
foreach (var type in FormTypeBuilderService.Value.GetModelTypes())
{
AddFormEntityType(type);
}
base.OnModelCreating(modelBuilder);
void AddFormEntityType(Type formType)
{
var entityType = modelBuilder.Model.FindEntityType(formType);
if (entityType == null)
{
modelBuilder.Model.AddEntityType(formType);
}
modelBuilder.Entity(formType).HasBaseType((Type)null!);
}
}
}
實現(xiàn)IModelCacheKeyFactory
我這里做了簡化處理,直接檢測了當前月份的變化,也可以通過實現(xiàn)一個靜態(tài)變量由外部動態(tài)改變。文章來源:http://www.zghlxwxcb.cn/news/detail-772060.html
public class DynamicModelCacheKeyFactory : IModelCacheKeyFactory
{
private static Guid RefreshToken = Guid.NewGuid();
public static Guid Refresh() => Guid.NewGuid();
public object Create(DbContext context, bool designTime)
{
return DateTime.Now.ToString("yyyyMM");
}
}
替換DbContext中的默認實現(xiàn)
services.AddDbContext<SampleDbContext>(opts =>
{
opts.ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactory>();
});
派生DbContext內(nèi)置方法
實現(xiàn)一個DynamicSet
對標Set<T>
,需要安裝System.Linq.Dynamic.Core
和Microsoft.EntityFrameworkCore.DynamicLinq
,即可使用lambda進行拼接查詢。文章來源地址http://www.zghlxwxcb.cn/news/detail-772060.html
public class SampleDbContext(DbContextOptions<SampleDbContext> options)
: DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 構(gòu)建所有的FormType
FormTypeBuilderService.BuildFormTypes();
// 將Type添加到DbContext上下文
foreach (var type in FormTypeBuilderService.Value.GetModelTypes())
{
AddFormEntityType(type);
}
base.OnModelCreating(modelBuilder);
void AddFormEntityType(Type formType)
{
var entityType = modelBuilder.Model.FindEntityType(formType);
if (entityType == null)
{
modelBuilder.Model.AddEntityType(formType);
}
modelBuilder.Entity(formType).HasBaseType((Type)null!);
}
}
public IQueryable DynamicSet(string tableId)
{
var type = FormTypeBuilderService.GetModelType(tableId);
return (IQueryable)GetType().GetTypeInfo().GetMethod("Set", Type.EmptyTypes)!.MakeGenericMethod(type)
.Invoke(this, null)!;
}
}
到了這里,關(guān)于Ef Core花里胡哨系列(5) 動態(tài)修改追蹤的實體、動態(tài)查詢的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!