WinUI 3 C# - Microsoft.Data.Sqlite.SqliteException

问题描述 投票:0回答:1

这是我真正遇到的一个问题。如果启用“Just My Code”,则下面的代码可以正常运行。如果禁用,则错误为:Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: '无法打开数据库文件'。'

创建包并上传到商店,然后应用程序无法打开,立即崩溃。

使用最新的 WinUI Template Studio 和 .net 8.0。

安装在单独的 DB 类库中的包:

public class DataDBContext : DbContext
{
    public static string DBPath { get; set; } = string.Empty;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite($"Filename={DBPath}", options =>
            {
                options.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName);
            });
        }
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Content>()
                    .HasKey(e => e.Id);

        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Content> Contents
    {
        get; set;
    }
}
public static async Task EnsureStoreAsync()
{
    try
    {
        using var db = new DataDBContext();
        await db.Database.MigrateAsync();
    }
    catch (Exception) {  }
}

然后在App.xaml.cs中

namespace Presenter;

public partial class App : Application
{
    public IHost Host
    {
        get;
    }    

    public App()
    {
        InitializeComponent();

        Host = Microsoft.Extensions.Hosting.Host.
        CreateDefaultBuilder().
        UseContentRoot(AppContext.BaseDirectory).
        ConfigureServices((context, services) =>
        {
            // Default Activation Handler
            services.AddTransient<ActivationHandler<LaunchActivatedEventArgs>, DefaultActivationHandler>();

            ....            

            // Configuration
            services.Configure<LocalSettingsOptions>(context.Configuration.GetSection(nameof(LocalSettingsOptions)));
        }).
        Build();

        UnhandledException += App_UnhandledException;
    }

    protected async override void OnLaunched(LaunchActivatedEventArgs args)
    {      
        base.OnLaunched(args);

        // Set the DB storage
        DataDBContext.DBPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Easy.db");

        // Initialize DB
        await DBService.EnsureStoreAsync();

        await App.GetService<IActivationService>().ActivateAsync(args);
    }

    public static T GetService<T>()
    where T : class
    {
        if ((App.Current as App)!.Host.Services.GetService(typeof(T)) is not T service)
        {
            throw new ArgumentException($"{typeof(T)} needs to be registered in ConfigureServices within App.xaml.cs.");
        }

        return service;
    }
}

可能是什么原因?

c# sqlite entity-framework-core dbcontext winui-3
1个回答
0
投票

我认为你应该这样使用:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var dbFile = @$"{AppContext.BaseDirectory}\Assets\DataBase\mydb.db";
        optionsBuilder.UseSqlite($"Data Source={dbFile}");
    }

我认为你应该使用数据源而不是文件名

© www.soinside.com 2019 - 2024. All rights reserved.