Is possible to create a database (Sql Server compact) on a given path if we use Entity framework with code-first approach?

前端 未结 1 714
予麋鹿
予麋鹿 2021-01-14 17:37

I\'m a bit confused about Entity framework, I would like to use code-first approach; infact I would like to write how my database tables are composed through class definitio

相关标签:
1条回答
  • 2021-01-14 18:01

    I just had the same problem a few days ago. Here's how I got it to work:

    In your application startup code add the following:

    using System.Data.Entity.Database;
    
    // ...
    
    DbDatabase.SetInitializer(new MyDbInitializer());
    DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory(
        "System.Data.SqlServerCe.4.0", 
        @"C:\Path\To\", 
        @"Data Source=C:\Path\To\DbFile.sdf");
    

    The Initializer should look something like this:

    using System.Data.Entity.Database;
    
    public class MyDbInitializer : CreateDatabaseIfNotExists<MyDbContext>
    {
        protected override void Seed(MyDbContext context)
        {
            // create some sample data
        }
    }
    

    If the CreateDatabaseIfNotExists is not the thing you want, there are more kinds of initializers you can use, or you can also create your own. More information on that can be found here:

    http://blog.oneunicorn.com/2011/03/31/configuring-database-initializers-in-a-config-file/

    Hope this helps.

    0 讨论(0)
提交回复
热议问题