can*_*stu 3 c# unit-of-work .net-framework-version entity-framework-6
我想每次都触发 OnModelCreating new DataContext(new Entity())......但是当我创建一个表的连接时,它可以工作。当为另一个表创建连接时,OnModelCreating 不再工作,所以因为我出错了,
the entity type <tableName> is not part of the model for the current context.
public class DataContext : DbContext
{
private BaseEntity _entity;
public DataContext(BaseEntity entity)
{
Database.Connection.ConnectionString = Parameters.ConnectionString;
_entity = entity;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
_entity.Map(modelBuilder); // this is dynamic fluent api here
}
}
Run Code Online (Sandbox Code Playgroud)
ta.speot.is 是正确的,因为模型构建器被缓存,所以 OnModelCreating 只触发一次。有几种情况需要再次执行 OnModelCreating。例如,当跨会话实施多租户时,可能需要再次触发 OnModelCreating。
第一次创建模型构建器时,EF 会缓存它以提高性能。它使用 IDbModelCacheKeyProvider.CacheKey 缓存。OnModelCreating 在找不到与 CacheKey 关联的 Cache 时触发。因此,要再次触发 OnModelCreating,必须更改 IDbModelCacheKeyProvider.CacheKey。
要更改缓存键,DbContext 类必须实现 IDbModelCacheKeyProvider。当在 IDbModelCacheKeyProvider 的 CacheKey 属性中返回新的缓存键时,再次触发 OnModelCreating 事件。
例如,请参见以下代码块:
public class TenantContext : DbContext, IDbModelCacheKeyProvider
{
string IDbModelCacheKeyProvider.CacheKey {
get { return tenentID.ToString(); }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Run Code Online (Sandbox Code Playgroud)
当tenantID 更改时,它会强制执行OnModelCreating,因为缓存可能不适用于新的tenantID。
注意:CacheKey 仅在非常紧急时才应更改。CacheKey 的频繁更改会降低性能。
| 归档时间: |
|
| 查看次数: |
3841 次 |
| 最近记录: |