我用VS 2015 ctp創建了一個web starter應用程序,我想添加一個內存存儲來做一些測試,但是當我嘗試讀取數據時,我收到了這條消息
數據存儲'SqlServerDataStore''InMemoryDataStore'可用。上下文只能配置為使用單個數據存儲。在設置服務時,通過在DbContext類或AddDbContext方法中覆蓋OnConfiguring來配置數據存儲。
如何創建第二個數據存儲區?現在我在ConfigureService
方法中有這一行
AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>()
.AddInMemoryStore()
.AddDbContext<WorkModel>( options => { options.UseInMemoryStore(persist: true); });
編輯 :看起來情景不明確。我有identy sql server dbcontext,我想添加第二個dbcontext,完全分開,我想在內存中運行。我正在尋找如何配置兩個不同的dbcontext,在這種情況下使用兩個不同的數據存儲。
第一個是Identity ApplicationDbContext,另一個是這樣的:
public class WorkModel : DbContext
{
public DbSet<Cliente> Clienti { get; set; }
public DbSet<Commessa> Commesse { get; set; }
protected override void OnModelCreating(ModelBuilder builder) {
builder.Entity<Cliente>().Key(cli => cli.ClienteId);
builder.Entity<Commessa>().Key(cli => cli.CommessaId);
}
}
或者你喜歡什麼樣的自定義dbcontext
可以使用一個具有多個數據存儲的DbContext
類型。但是,對於.AddDbContext()
調用,它不會很好。下面是一個如何使用.ConfigureServices()
完全脫離圖片的示例。
class MyContext : DbContext
{
bool _useInMemory;
public MyContext(bool useInMemory)
{
_useInMemory = useInMemory;
}
protected override void OnConfiguring(DbContextOptions options)
{
if (_useInMemory)
{
options.UseInMemoryStore(persist: true);
}
else
{
options.UseSqlServer();
}
}
}
然後,您可以實例化指定要使用的提供程序的上下文。
var inMemoryContext = new MyContext(useInMemory: true);
var sqlServerContext = new MyContext(useInMemory: false);