EF 5 + SQL Server CE 4: How to specify custom location for database file?

前端 未结 4 1500
醉梦人生
醉梦人生 2020-12-15 13:32

I am developing a client system that needs a small local database. I want to avoid installation of SQL Server Express and have decided to go with SQL Server 4.

I use

相关标签:
4条回答
  • 2020-12-15 13:41

    For EF 6

    I arrived at this answer thanks to Matthias's post, but included some worthwhile info from Entity Framework Code-Based Configuration (EF6 onwards).

    To specify a custom database location you will need to do some configuration. Configuration for an Entity Framework application can be specified in a config file (app.config/web.config) or through code. The latter is known as code-based configuration. Given that my project required the database location to be set dynamically, I went with the code-based configuration, which is described below.

    (Note that the config file takes precedence over code-based configuration. In other words, if a configuration option is set in both code and in the config file, then the setting in the config file is used.)

    According to EF documentation (above link) there are 4 approaches to implement your custom configuration,which include: Using DbConfiguration, Moving DbConfiguration, Setting DbConfiguration explicitly, and Overriding DbConfiguration.

    Using DbConfiguration

    Code-based configuration in EF6 and above is achieved by creating a subclass of System.Data.Entity.Config.DbConfiguration. The following guidelines should be followed when subclassing DbConfiguration:

    • Create only one DbConfiguration class for your application. This class specifies app-domain wide settings.

    • Place your DbConfiguration class in the same assembly as your DbContext class. (See the Moving DbConfiguration section if you want to change this.)

    • Give your DbConfiguration class a public parameterless constructor.

    • Set configuration options by calling protected DbConfiguration methods from within this constructor.

    Following these guidelines allows EF to discover and use your configuration automatically by both tooling that needs to access your model and when your application is run.

    Example (modified from Matthias's answer):

    public class MyDbConfiguration : DbConfiguration
    {
        public MyDbConfiguration()
        {
            SetProviderServices(SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance);
            //var directory Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var directory = @"C:\Users\Evan\Desktop\TestFolder"; // Directory may or may not already exist
            Directory.CreateDirectory(directory);   // create directory if not exists         
            var path = Path.Combine(directory, @"ApplicationName\MyDatabase.sdf");          
            var connectionString = string.Format(@"Data Source={0}",path);
            SetDefaultConnectionFactory(new SqlCeConnectionFactory(SqlCeProviderServices.ProviderInvariantName, "", connectionString));
        }
    } 
    

    Note that the config file does not need to be altered unless there are existing configuration settings that override your custom configuration. Also, I changed the directory to illustrate that While EF is capable of creating a new database if it doesn't already exist, it will not create parent directories, which is why I included this line: Directory.CreateDirectory(directory). Given that this approach worked for my project I didn't explore the remaining 3 configuration methods, but you can find info on them in the link provided above and I will include the documentation here as a reference in case the link breaks.

    Moving DbConfiguration

    There are cases where it is not possible to place your DbConfiguration class in the same assembly as your DbContext class. For example, you may have two DbContext classes each in different assemblies. There are two options for handling this.

    The first option is to use the config file to specify the DbConfiguration instance to use. To do this, set the codeConfigurationType attribute of the entityFramework section. For example:

    <entityFramework codeConfigurationType="MyNamespace.MyDbConfiguration, MyAssembly"> 
        ...Your EF config... 
    </entityFramework>
    

    The value of codeConfigurationType must be the assembly and namespace qualified name of your DbConfiguration class.

    The second option is to place DbConfigurationTypeAttribute on your context class. For example:

    [DbConfigurationType(typeof(MyDbConfiguration))] 
    public class MyContextContext : DbContext 
    { 
    }
    

    The value passed to the attribute can either be your DbConfiguration type - as shown above - or the assembly and namespace qualified type name string. For example:

    [DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")] 
    public class MyContextContext : DbContext 
    { 
    }
    

    Setting DbConfiguration explicitly

    There are some situations where configuration may be needed before any DbContext type has been used. Examples of this include:

    • Using DbModelBuilder to build a model without a context
    • Using some other framework/utility code that utilizes a DbContext where that context is used before your application context is used

    In such situations EF is unable to discover the configuration automatically and you must instead do one of the following:

    • Set the DbConfiguration type in the config file, as described in the Moving DbConfiguration section above
    • Call the static DbConfiguration.SetConfiguration method during application startup

    Overriding DbConfiguration

    There are some situations where you need to override the configuration set in the DbConfiguration. This is not typically done by application developers but rather by thrid party providers and plug-ins that cannot use a derived DbConfiguration class.

    For this, EntityFramework allows an event handler to be registered that can modify existing configuration just before it is locked down. It also provides a sugar method specifically for replacing any service returned by the EF service locator. This is how it is intended to be used:

    • At app startup (before EF is used) the plug-in or provider should register the event handler method for this event. (Note that this must happen before the application uses EF.)
    • The event handler makes a call to ReplaceService for every service that needs to be replaced.

    For example, to repalce IDbConnectionFactory and DbProviderService you would register a handler something like this:

    DbConfiguration.Loaded += (_, a) => 
       { 
           a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s)); 
           a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s)); 
       };
    

    In the code above MyProviderServices and MyConnectionFactory represent your implementations of the service.

    You can also add additional dependency handlers to get the same effect.

    Note that you could also wrap DbProviderFactory in this way, but doing so will only effect EF and not uses of the DbProviderFactory outside of EF. For this reason you’ll probably want to continue to wrap DbProviderFactory as you have before.

    You should also keep in mind the services that you run externally to your application - e.g. running migrations from Package Manager console. When you run migrate from the console it will attempt to find your DbConfiguration. However, whether or not it will get the wrapped service depends on where the event handler it registered. If it is registered as part of the construction of your DbConfiguration then the code should execute and the service should get wrapped. Usually this won’t be the case and this means that tooling won’t get the wrapped service.

    0 讨论(0)
  • 2020-12-15 13:58

    Ah, I finally got it right!

    I include the adjusted code if someone else has the same problem. The trick was to set the connection string on the Database.DefaultConnectionFactory

        private MyApplicationDataContext()
        { }
    
        public static MyApplicationDataContext CreateInstance()
        {
            var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var path = Path.Combine(directory, @"ApplicationName\MyDatabase.sdf");
    
            // Set connection string
            var connectionString = string.Format("Data Source={0}", path);
            Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", connectionString);
    
            return new MyApplicationDataContext();
        }
    
    0 讨论(0)
  • 2020-12-15 13:58

    In EF 6 this can be done with DbConfiguration:

    App.config:

    <entityFramework codeConfigurationType="MyDbConfiguration, MyAssembly">
    </entityFramework>
    

    And inside your assembly create a class like:

    public class MyDbConfiguration : DbConfiguration
    {
        public MyDbConfiguration()
        {
            SetProviderServices(SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance);
            var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var path = Path.Combine(directory, @"ApplicationName\MyDatabase.sdf");          
            var connectionString = string.Format(@"Data Source={0}",path);
            SetDefaultConnectionFactory(new SqlCeConnectionFactory(SqlCeProviderServices.ProviderInvariantName, "", connectionString));
        }
    }  
    
    0 讨论(0)
  • 2020-12-15 14:04

    The SqlCeConnection instance is used to connect to Sql Ce database file. If I want to connect to MSSQL database, I will use SqlConnectionStringBuilder and SqlConnection instances to build my DbConnection instance.

    // The ctor for `DbConnection`.
    private MyApplicationDataContext(DbConnection conn) : base(conn, true) {}
    
    public static MyApplicationDataContext CreateInstance()
    {
        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var path = Path.Combine(directory, @"ApplicationName\MyDatabase.sdf");
    
        // Connection string builder for `Sql ce`
        SqlCeConnectionStringBuilder sb = new SqlCeConnectionStringBuilder();
        sb.DataSource = path;
    
        // DbConnection for `Sql ce`
        SqlCeConnection dbConn = new SqlCeConnection(sb.ToString());
        return new MyApplicationDataContext(dbConn);
    }
    
    0 讨论(0)
提交回复
热议问题