How to map an Entity framework model to a table name dynamically

本文介绍了一种使用Code First方法在Entity Framework中实现单个模型到多个表名动态映射的技术。通过创建一个特殊的库和利用CSharpCodeProvider,作者实现了根据不同表名实例化不同的DbContext,从而解决了动态表映射的问题。

Using a code-first approach I'd like to map a single model to multiple table names dynamically. Currently I can do something like modelBuilder.Entity(Of Person)().MapSingleType().ToTable("Managers") but as the OnModelCreating method is only called once I can't map it to other table names on the fly.

In our current LinqToSql version we're overriding the MetaModel.GetTable() and returning a new TableAttribute with our dynamic name. I haven't found an attribute like that in EF (even if there were I wouldn't know how to override that yet). So my question is: Is it possible to do this (yet)?

Update

I've found that I can prevent the OnModelCreating method from caching the mappings by calling

modelBuilder.CacheForContextType = false; 

As a result I can assign table definitions on instantiation of the object. This isn't quite how I wanted to do it but it works.

Update

Oh boy, was the above a big mistake...Caching exists for a reason! :) So I'm back to square one with POCO object mapping. I'll post an update if I figure out a solution.

Final

Incase anybody cares how I've currently solved this issue, here you go:

First I created a separate library with the POCO tables and an Interface

public interface IDataContext { 
   
System.Data.Entity.DbSet<TableGeneric> TableGeneric { get; set; } 
 
   
int SaveChanges(); 
} 
 
 
public class TableGeneric { 
   
[Key] 
   
public int Column1 { get; set; } 
   
public string Column2 { get; set; } 
   
public DateTime Column3 { get; set; } 
   
public string Column4 { get; set; } 
   
public string Column5 { get; set; } 
} 

Then, using the CSharpCodeProvider I created a class that takes the following template and turns it into a type definition:

class DataContext : System.Data.Entity.DbContext, IDataContext { 
   
public System.Data.Entity.DbSet<TableGeneric> TableGeneric { get; set; } 
 
   
protected override void OnModelCreating(ModelBuilder modelBuilder) { 
        modelBuilder 
           
.Entity<ContextTesting.Interfaces.EF.TableGeneric() 
               
.MapSingleType() 
               
.ToTable("$TableName$"); 
   
} 
} 

With the generated type I'm able to create an instance so here we go

Type typeAccountants = BuildContext.CreateGenericTable("Accountants"); 
IDataContext context = (IDataContext)Activator.CreateInstance(typeAccountants); 

Then the rest is just as if you had a normal DataContext. Hope this helps someone else.

Entity Framework 5 的 `OnModelCreating` 方法中外部传送 `ToTable` 参数,可以通过以下步骤实现: ### 1. 定义一个包含表名的配置类 首先,创建一个配置类,该类用于存储要传递的表名。 ```csharp public class TableNameConfiguration { public string TableName { get; set; } } ``` ### 2. 修改 DbContext 类以接收配置 在 `DbContext` 类中添加一个构造函数,该构造函数接收 `TableNameConfiguration` 对象,并在 `OnModelCreating` 方法中使用该对象的表名。 ```csharp using System.Data.Entity; using System.Data.Entity.Infrastructure.Annotations; using System.ComponentModel.DataAnnotations.Schema; public class YourDbContext : DbContext { private readonly TableNameConfiguration _tableNameConfig; public YourDbContext(TableNameConfiguration tableNameConfig) { _tableNameConfig = tableNameConfig; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { if (_tableNameConfig != null && !string.IsNullOrEmpty(_tableNameConfig.TableName)) { // 假设这里有一个名为 YourEntity 的实体类 modelBuilder.Entity<YourEntity>() .ToTable(_tableNameConfig.TableName); } base.OnModelCreating(modelBuilder); } } ``` ### 3. 使用配置创建 DbContext 实例 在使用 `DbContext` 时,创建 `TableNameConfiguration` 对象并将其传递给 `DbContext` 的构造函数。 ```csharp class Program { static void Main() { var tableNameConfig = new TableNameConfiguration { TableName = "YourTableName" }; using (var context = new YourDbContext(tableNameConfig)) { // 可以在这里执行数据库操作 } } } ``` ### 解释 - 通过创建 `TableNameConfiguration` 类,可以将表名作为参数传递给 `DbContext`。 - 在 `DbContext` 的构造函数中接收该配置对象,并在 `OnModelCreating` 方法中使用该对象的表名来调用 `ToTable` 方法。 - 这样,就可以在外部灵活地指定表名,而不需要在 `OnModelCreating` 方法中硬编码表名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值