EF DBConfiguration associated automatically to DBContext without annotation

c# dbcontext entity-framework

Question

Using the latest EF (6.1.1) and EF for SQL Server Compact (6.1.1) that pulls in Compact 4.0. Target is Net 4.5.1

Looking to code up my EF and later on piece it together with StructureMap. Created a DbConfiguration class:

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

And a context:

 public class MyContext : DbContext
 {
   public MyContext(String connection) : base(connection) {}
   ....
 }

With XUnit I run:

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

The test case successfully creates (and seeds through the initializer) my Compact database. But there is a bunch of implicit stuff happening behind the scenes that I don't get.

For example, I don't need to have the following annotation on my MyContext class:

 [DbConfigurationType(typeof(MyConfiguration))]

EF must be smart enough to see that I have a MyConfiguration class that extends DbConnection and use it. Or? I can also remove the MyConfiguration all together and the test case will still generate a database (obviously not seeded). How?

I would love to be able with code to assign the DbConfiguration to a specific DbContext without going through static:

 static MyContext()
 {
   DbConfiguration.set(new MyConfiguration());
 }

Reason being is to also for different "profiles" with StructureMap. Any ideas?

1
4
9/22/2014 9:20:20 AM

Accepted Answer

Yes and No in your web.config you should have a section like this

<contexts>
  <context type="<DAL.MyContext, DAL">
    <databaseInitializer type="DAL.MyConfiguration, DAL" />
  </context>
</contexts>

Where DAL would be where your MyContext and MyConfiguration exist

[EDIT]

to do it only in code you must use the static method DbConfiguration.SetConfiguration(DbConfiguration configuration) as per here and it must be set before any use of the context.

5
9/22/2014 1:10:26 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow