C# 如何修复:无法使用资产文件夹中已有的sqlite.db激活windows应用商店应用程序-CRUD UWP MVVM模型

C# 如何修复:无法使用资产文件夹中已有的sqlite.db激活windows应用商店应用程序-CRUD UWP MVVM模型,c#,xaml,uwp,C#,Xaml,Uwp,添加将Repository.db从资产文件夹复制到本地存储的方法后的App.xaml.cs代码 如果我取消对App.xaml.cs sqlite.db代码的注释,应用程序将在调试后运行,而不加载数据。当我的插入点在App.xaml.cs中的Onloadlaunched()方法中的UseSqlite()方法之后被去除时。但是,引发的未经处理的异常会指向SqlTutorialRepository.cs中的EnsureCreated()方法 using CustomerOrders.Models; u

添加将Repository.db从资产文件夹复制到本地存储的方法后的App.xaml.cs代码 如果我取消对App.xaml.cs sqlite.db代码的注释,应用程序将在调试后运行,而不加载数据。当我的插入点在App.xaml.cs中的Onloadlaunched()方法中的UseSqlite()方法之后被去除时。但是,引发的未经处理的异常会指向SqlTutorialRepository.cs中的EnsureCreated()方法

using CustomerOrders.Models;
using CustomerOrders.Repository;
using CustomerOrders.Views;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace CustomerOrders
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        public static ITutorialRepository Repository { get; set; }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void  OnLaunched(LaunchActivatedEventArgs e)
        {
            UseSqlite();

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(typeof(CustomerListPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }
        }

        public static void  UseSqlite() 
        {

            string demoDatabasePath = Package.Current.InstalledLocation.Path + @"\Assets\Repository.db";
            string databasePath = ApplicationData.Current.LocalFolder.Path + @"\Repository.db";
            if (!File.Exists(databasePath))
            {
                File.Copy(demoDatabasePath, databasePath);
            }
            var dbOptions = new DbContextOptionsBuilder<CustomerContext>().UseSqlite("Data Source=" + databasePath);
            Repository = new SqlTutorialRepository(dbOptions);
        }
        public async Task CopyDatabase()
        {
            bool isDatabaseExisting = false;

            try
            {
                StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Repository.db");
                isDatabaseExisting = true;
            }
            catch
            {
                isDatabaseExisting = false;
            }

            if (!isDatabaseExisting)
            {
                StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("Repository.db");
                await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
            }
        }


        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}

// SqlTutorialRepository.cs

using CustomerOrders.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomerOrders.Repository
{
    public class SqlTutorialRepository : ITutorialRepository
    {
        private DbContextOptions<CustomerContext> _dbOptions;
        public SqlTutorialRepository(DbContextOptionsBuilder<CustomerContext> dbOptionsBuilder)
        {
            _dbOptions = dbOptionsBuilder.Options;
            using(var db = new CustomerContext(_dbOptions))
            {
                db.Database.EnsureCreated();
            }

        }
  

  public ICustomerRepository Customers => new SqlCustomerRepository(new CustomerContext(_dbOptions));
}

}
使用CustomerOrders.Models;
使用CustomerOrders.Repository;
使用CustomerOrders.Views;
使用Microsoft.EntityFrameworkCore;
使用制度;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用System.Runtime.InteropServices.WindowsRuntime;
使用System.Threading.Tasks;
使用Windows.ApplicationModel;
使用Windows.ApplicationModel.Activation;
使用Windows基金会;
使用Windows。
使用Windows.Storage;
使用Windows.UI.Xaml;
使用Windows.UI.Xaml.Controls;
使用Windows.UI.Xaml.Controls.Primitives;
使用Windows.UI.Xaml.Data;
使用Windows.UI.Xaml.Input;
使用Windows.UI.Xaml.Media;
使用Windows.UI.Xaml.Navigation;
命名空间自定义顺序
{
/// 
///提供特定于应用程序的行为以补充默认应用程序类。
/// 
密封部分类应用程序:应用程序
{
公共静态ITutorialRepository存储库{get;set;}
/// 
///初始化singleton应用程序对象。这是编写代码的第一行
///已执行,因此是main()或WinMain()的逻辑等价物。
/// 
公共应用程序()
{
this.InitializeComponent();
这个.Suspending+=OnSuspending;
}
/// 
///当最终用户正常启动应用程序时调用。其他入口点
///将在启动应用程序以打开特定文件时使用。
/// 
///有关启动请求和过程的详细信息。
仅启动受保护的覆盖无效(启动ActivatedEventArgs e)
{
UseSqlite();
Frame rootFrame=Window.Current.Content作为Frame;
//当窗口已经有内容时,不要重复应用程序初始化,
//只需确保窗口处于活动状态
if(rootFrame==null)
{
//创建一个框架作为导航上下文并导航到第一页
rootFrame=新框架();
rootFrame.NavigationFailed+=OnNavigationFailed;
如果(例如,PreviousExecutionState==ApplicationExecutionState.Terminated)
{
//TODO:从先前挂起的应用程序加载状态
}
//将框架放置在当前窗口中
Window.Current.Content=rootFrame;
}
如果(如预启动激活==错误)
{
if(rootFrame.Content==null)
{
//导航堆栈未还原时,请导航到第一页,
//通过将所需信息作为导航传递来配置新页面
//参数
导航(typeof(CustomerListPage),例如参数);
}
//确保当前窗口处于活动状态
Window.Current.Activate();
}
}
公共静态void UseSqlite()
{
字符串demoDatabasePath=Package.Current.InstalledLocation.Path+@“\Assets\Repository.db”;
字符串databasePath=ApplicationData.Current.LocalFolder.Path+@“\Repository.db”;
如果(!File.Exists(databasePath))
{
复制(数据库路径、数据库路径);
}
var dbOptions=new DbContextOptionsBuilder().UseSqlite(“数据源=“+databasePath”);
Repository=新的SqlTutorialRepository(dbOptions);
}
公共异步任务CopyDatabase()
{
bool isDatabaseExisting=false;
尝试
{
StorageFile StorageFile=Wait ApplicationData.Current.LocalFolder.GetFileAsync(“Repository.db”);
isDatabaseExisting=true;
}
抓住
{
isDatabaseExisting=false;
}
如果(!isDatabaseExisting)
{
StorageFile databaseFile=await Package.Current.InstalledLocation.GetFileAsync(“Repository.db”);
等待databaseFile.copyanc(ApplicationData.Current.LocalFolder);
}
}
/// 
///当导航到某个页面失败时调用
/// 
///导航失败的帧
///有关导航失败的详细信息
void OnNavigationFailed(对象发送方,NavigationFailedEventArgs e)
{
抛出新异常(“加载页面失败”+e.SourcePageType.FullName);
}
/// 
///在挂起应用程序执行时调用。应用程序状态已保存
///不知道应用程序是否会随内容一起终止或恢复
///记忆仍然完好无损。
/// 
///挂起请求的源。
///有关暂停请求的详细信息。
暂停时的私有void(对象发送方,SuspendingEventArgs e)
{
var deleral=e.SuspendingOperation.getdeleral();
//TODO:保存应用程序状态并停止任何后台活动
延迟。完成();
}
}
}
//SqlTutorialRepository.cs
使用CustomerOrders.Models;
使用Microsoft.EntityFrameworkCore;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间CustomerOrders.Repo