问题描述
我想触发每个new DataContext(new Entity())
的OnModelCreating ...但是,当我创建表的连接时,它可以工作.当为另一个表创建连接时,OnModelCreating不会再起作用,所以因为出现错误,
I want to fire OnModelCreating every new DataContext(new Entity())
...But when i create a connection of a table , it works. When create a connection for another table, OnModelCreating doesnt work again, so because i got error,
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
}
}
推荐答案
ta.speot.is是对的,OnModelCreating仅触发一次,因为对ModelBuilder进行了缓存.有几种情况需要再次执行OnModelCreating.例如,当跨会话实施多租户时,可能需要再次触发OnModelCreating.
ta.speot.is is right that OnModelCreating fires only once because modelBuilder is cached. There are several cases when OnModelCreating is required to execute again. For example when multi-tenancy is implemented across sessions then one may require to fire OnModelCreating again.
首次创建modelBuilder时,EF将其缓存以提高性能.使用IDbModelCacheKeyProvider.CacheKey对其进行缓存.当找不到与CacheKey关联的Cache时,将触发OnModelCreating.因此,要再次触发OnModelCreating,必须更改IDbModelCacheKeyProvider.CacheKey.
When modelBuilder is created first time, then EF caches it to increase performance. it is cached using IDbModelCacheKeyProvider.CacheKey. OnModelCreating fires when it does not find Cache associated with CacheKey. So to get OnModelCreating fired again IDbModelCacheKeyProvider.CacheKey must be changed.
要更改缓存键,DbContext类必须实现IDbModelCacheKeyProvider.在IDbModelCacheKeyProvider的CacheKey属性中返回新的缓存键时,将再次触发OnModelCreating事件.
To change cache key, DbContext class must implement IDbModelCacheKeyProvider. When new cache key is returned In CacheKey property of IDbModelCacheKeyProvider then OnModelCreating event fires again.
例如,请参见以下代码块:
For example see following code block:
public class TenantContext : DbContext, IDbModelCacheKeyProvider
{
string IDbModelCacheKeyProvider.CacheKey {
get { return tenentID.ToString(); }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
更改tenantID后,由于缓存可能无法用于新的tenantID,它会强制执行OnModelCreating.
When tenantID is changed, it forces OnModelCreating to execute because cache might not be available for new tenantID.
注意:仅在非常紧急时才应更改CacheKey.频繁更改CacheKey会降低性能.
Note: CacheKey should be changed only if it is very urgent. Frequent change in CacheKey will decrease performance.
这篇关于如何强制启动OnModelCreating每个初始化的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!