Deploy a WPF program and update the database if required

末鹿安然 提交于 2019-12-11 03:43:02

问题


I'm creating a WPF application that uses a LocalDB instance (which is provided by the ClickOnce installer).

The program uses a database to store userdata. When the application is deployed for the very first time, I want to create a LocalDB where some data is inserted upon initialization.

When I later provide an update to the program (which may include schema changes), I do not want to lose any userdata.

I'm using EF Code-First and this is my DbContext:

public class MyContext : DbContext
{
    public DbSet<Stuff> Premises { get; set; }
    public DbSet<Person> Persons { get; set; }


    private static MyContext _Current;

    public static MyContext Current
    {
        get
        {
            if (_Current == null)
            {
                _Current = new MyContext();
            }
            return _Current;
        }
    }

    protected MyContext()
    {
        //Some data to insert on the first time
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Stuff>().HasMany(p => p.Persons).WithRequired(m => m.Stuff);
    }
}

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <connectionStrings>
    <add name="MyContext"
    connectionString="data source=(LocalDB)\mssqllocaldb;Integrated Security=True"
    providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Am I correct in thinking that adding my development .mdf file will always overwrite the userdata when I update via ClickOnce?

How can I let EF create the schema for the first time, update when there's changes, and never lose any userdata?

来源:https://stackoverflow.com/questions/29320975/deploy-a-wpf-program-and-update-the-database-if-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!