更新我的问题,顺便说一句,无论谁投了反对票,都可以提供建设性的评论..
使用最新的 WinUI Template Studio 和 .net 8.0。
应用程序设置.json
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Filename=easy.db"
}
}
public class DataDBContext : DbContext
{
public DataDBContext(DbContextOptions<DataDBContext> options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlite(connectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Content>().HasKey(e => e.Id);
}
public DbSet<Content> Contents
{
get; set;
}
}
public class DataDBContextFactory : IDesignTimeDbContextFactory<DataDBContext>
{
public DataDBContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<DataDBContext>();
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlite(connectionString);
return new DataDBContext(optionsBuilder.Options);
}
}
然后在App.xaml.cs中
Host = Microsoft.Extensions.Hosting.Host.
CreateDefaultBuilder().
UseContentRoot(AppContext.BaseDirectory).
ConfigureServices((context, services) =>
{
var connectionString = context.Configuration.GetConnectionString("DefaultConnection");
// Default Activation Handler
services.AddTransient<ActivationHandler<LaunchActivatedEventArgs>, DefaultActivationHandler>();
// Other Activation Handlers
services.AddDbContext<DataDBContext>(options => options.UseSqlite(connectionString));
services.AddTransient<DBService>();
....
}).
Build();
}
它可以在 Visual Studio 中运行,但一旦部署并从开始菜单打开,就会崩溃,错误模块路径:C:\Program Files\WindowsApps\Microsoft.WindowsAppRuntime.1.4_4000.1049.117.0_x64__8wekyb3d8bbwe\Microsoft.ui.xaml.dll
有人可以让我走上正轨吗?
我认为你应该这样使用:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var dbFile = @$"{AppContext.BaseDirectory}\Assets\DataBase\mydb.db";
optionsBuilder.UseSqlite($"Data Source={dbFile}");
}
我认为你应该使用数据源而不是文件名