EF DBConfiguration自动关联到DBContext,无需注释

Mat*_*ell 3 c# entity-framework dbcontext

将最新的EF(6.1.1)和EF用于SQL Server Compact(6.1.1),将其引入Compact 4.0。目标是净4.5.1

希望对我的EF进行编码,然后再与StructureMap一起使用。创建了一个DbConfiguration类:

 public class MyConfiguration : DbConfiguration
 {
   SetDatabaseInitializer<MyContext>(new MyInitializer());
   SetProviderServices(SqlCeProviderServices.ProviderInvariantName,
                            SqlCeProviderServices.Instance);
 }
Run Code Online (Sandbox Code Playgroud)

和上下文:

 public class MyContext : DbContext
 {
   public MyContext(String connection) : base(connection) {}
   ....
 }
Run Code Online (Sandbox Code Playgroud)

使用XUnit我运行:

 using (var ctx = new MyContext(String.Format("Data Source={0}", Path.Combine(databasePath, databaseName)))) {
   ctx.Database.Initialize(true)
 }
Run Code Online (Sandbox Code Playgroud)

测试用例成功创建了Compact数据库(并通过初始化程序植入了种子)。但是在幕后发生了很多我不了解的隐性事情。

例如,我不需要在MyContext类上使用以下注释:

 [DbConfigurationType(typeof(MyConfiguration))]
Run Code Online (Sandbox Code Playgroud)

EF必须足够聪明才能看到我有一个MyConfiguration类来扩展DbConnection并使用它。要么?我还可以一起删除MyConfiguration,并且测试用例仍将生成一个数据库(显然没有种子)。怎么样?

我希望能够使用代码将DbConfiguration分配给特定的DbContext,而无需通过静态操作:

 static MyContext()
 {
   DbConfiguration.set(new MyConfiguration());
 }
Run Code Online (Sandbox Code Playgroud)

原因是也要与StructureMap使用不同的“配置文件”。有任何想法吗?

Ped*_*Kid 5

是和否在您的web.config中,您应该有一个这样的部分

<contexts>
  <context type="<DAL.MyContext, DAL">
    <databaseInitializer type="DAL.MyConfiguration, DAL" />
  </context>
</contexts>
Run Code Online (Sandbox Code Playgroud)

DAL将在您MyContextMyConfiguration存在

[编辑]

要仅在代码中执行此操作,必须DbConfiguration.SetConfiguration(DbConfiguration configuration) 按照此处的方法使用static方法,并且必须在使用上下文之前对其进行设置。