.net 6 efcore一个model映射到多张表(非使用IEntityTypeConfiguration)

现在有两张表,结构一模一样,我又不想创建两个一模一样的model,就想一个model映射到两张表

废话不多说直接上代码

  1. 安装依赖包
  2. 创建model
csharp 复制代码
namespace oneModelMultiTable.Model
{
    public class Test
    {
        public int id { get; set; }

        public string name { get; set; }

        public string tablename { get; set; }
    }
}
  1. 创建DBContext
    我们需要使用tablename 动态指定表名,因此需要在DBContext中添加这个属性
csharp 复制代码
namespace oneModelMultiTable
{
    public class DBHelper:DbContext
    {
        public DbSet<Test> testConfigs { get; set; }

        public string tablename { get; set; }
        public DBHelper(DbContextOptions<DBHelper> options):base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Test>(b =>
            {
                b.ToTable(tablename);
                b.HasKey(p => p.id);
            });

            base.OnModelCreating(modelBuilder);

            //modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
    }
}
  1. 创建DynamicModelCacheKeyFactory 继承IModelCacheKeyFactory
csharp 复制代码
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace oneModelMultiTable
{
    public class DynamicModelCacheKeyFactory : IModelCacheKeyFactory
    {

        public object Create(DbContext context, bool designTime)
        {
            object p = context is DBHelper dynamicContext
                ? (context.GetType(), dynamicContext.tablename)
                : (object)context.GetType();
            return p;
        }
    }
}
  1. 依赖注入
csharp 复制代码
builder.Services.AddDbContext<DBHelper>(options =>
{
    options.UseNpgsql(@"Host=192.168.214.133;Port=32222;Database=postgresdb;Username=postgresadmin;Password=admin123")
    .ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactory>();
});
  1. 创建controller
csharp 复制代码
using Microsoft.AspNetCore.Mvc;
using oneModelMultiTable.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace oneModelMultiTable.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        public readonly DBHelper dBHelper;

        public TestController(DBHelper _DBHelper)
        {
            dBHelper = _DBHelper;
        }

        // GET: api/<TestController>
        [HttpGet]
        public List<Test> Get(string tablename)
        {
            dBHelper.tablename = tablename;
            return dBHelper.testConfigs.ToList();
        }
    }
}

原理

你可能想通过ToTable()方法来更改表名,但是我们如何在OnModelCreating方法中更改表名呢?当EF构建模型时,它只运行OnModelCreating一次。

对于这个场景,我们需要通过使用IModelCacheKeyFactory 来更改默认映射,它允许我们连接到模型缓存机制,以便EF可以根据其属性创建不同的模型。

EF使用IModelCacheKeyFactory为模型生成缓存键。

https://yanxiaodi.medium.com/mapping-the-model-to-multiple-tables-with-entityframework-core-b46bdeed8661

https://medium.com/@pawel.gerr/entity-framework-core-changing-database-schema-at-runtime-dcf1211768c6

https://github.com/xdqt/asp.net-core/tree/master/oneModelMultiTable

相关推荐
心念枕惊6 小时前
OpenClaw.NET 重大更新:Goal 机制登场,让 AI Agent 不再“半途而废“
.net
geovindu7 小时前
CSharp:Chain of Responsibility Pattern
开发语言·后端·设计模式·c#·.net·责任链模式·行为模式
TDengine (老段)9 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
逻极1 天前
C# 从入门到精通:现代云原生与AI应用开发实战
ai·云原生·c#·.net
geovindu2 天前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
海盗12342 天前
微软技术周报2026-07-27
microsoft·c#·.net
iReachers3 天前
.NET项目集成混淆加密:自动化保护DLL和EXE
.net·代码保护·自动构建·msbuild·c#混淆
完美火龙篇 四月的友3 天前
通俗易懂,什么是.NET?什么是.NET Framework?什么是.NET Core?
.net·.netcore
柠檬香的3 天前
CsGrafeq: 比 Desmos 更“能折腾”的几何函数画板(.NET + Avalonia)
.net