问题描述
我正在使用 EF Core v. 5.0 和 sqlite DB,我正在尝试将 DbSet 动态添加到我的 DbContext。我已经遵循并重新改编本指南到 EF Core:https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/ 并且我意识到这个 DbContext 类:
internal class GenericAppContext : DbContext
{
public GenericAppContext()
{
//disable the EF cache system to execute every running the OnModelCreating method.
//ATTENTION: This is a performance loss action!
this.ChangeTracker.LazyLoadingEnabled = false;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
//if "bin" is present,remove all the exceeding path starting from "bin" word
if (baseDir.Contains("bin"))
{
int index = baseDir.IndexOf("bin");
baseDir = baseDir.Substring(0,index);
}
options.Usesqlite($"Data Source={baseDir}Database\\Testsqlite.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
MethodInfo addMethod = typeof(ModelBuilder).getmethods().First(e => e.Name == "Entity");
foreach (var assembly in AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.GetName().Name != "EntityFramework"))
{
IEnumerable<Type> configTypes = assembly
.GetTypes()
.Where(t => t.BaseType != null
&& t.BaseType.IsGenericType
&& t.BaseType.GetGenericTypeDeFinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in configTypes)
{
Type entityType = type.BaseType.GetGenericArguments().Single();
object entityConfig = assembly.CreateInstance(type.FullName);
addMethod?.MakeGenericmethod(entityType)
.Invoke(modelBuilder,new object[] { });
}
}
}
}
internal class Blog : EntityTypeConfiguration<Blog>
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
internal class Article : EntityTypeConfiguration<Article>
{
[Key]
public int Id { get; set; }
public string Body { get; set; }
}
这是我如何初始化 DbContext,在“tables”变量中,我可以看到使用 context.Model.GetRelationalModel().Tables.ToList() 动态添加的“文章”表)
public static string TestMethod()
{
using (var context = new GenericAppContext())
{
string result = string.Empty;
//Ensures that the database for the context exists. If it exists,no action is taken. If it does not exist then the database and all its schema are created.
context.Database.EnsureCreated();
List<ITable> tables = context.Model.GetRelationalModel().Tables.ToList();
}
}
此时,我成功看到动态添加的“文章”类,但是我无法使用Linq查询“文章”,当然,因为它在DbContext中并不存在.
有没有办法对像“文章”这样的动态 DbSet 添加表使用 Linq?
解决方法
最后我使用“Linq.Dynamic.Core”解决了这个问题,它允许您使用 Linq 并将 lambda 表达式编写为字符串,等等,here more info about Dynamic Linq。 >
这里是我如何修改之前显示的 TestMethod(),以及我如何对通过我的“GenericContextApp" 类。
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
public static string TestMethod()
{
using (var context = new GenericAppContext())
{
string result = string.Empty;
//Ensures that the database for the context exists. If it exists,no action is taken. If it does not exist then the database and all its schema are created.
context.Database.EnsureCreated();
IEnumerable<IEntityType> contextEntitiesList = context.Model.GetEntityTypes();
IQueryable<IEntityType> entitiesList = contextEntitiesList.Select(p => p).ToList().AsQueryable();
//Query against the dinamycally added "Article" table. It will return the SQL query as a string.
result = context.Query("Your.Complete.Namespace.Article").Where("Body == \"ciao\"").ToQueryString();
return result;
}
}