【发布时间】:2021-01-22 10:37:38
【问题描述】:
我有一个带有实体框架核心&sqlite 的 .net core 3.1 WPF 示例项目。
这是 Mainwindow.XAML 中的代码:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<string> ObjectList { get; set; }
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
Database.AppDBContext Context = new Database.AppDBContext();
ObjectList = new ObservableCollection<string>(Context.TestTable.Select(X => X.name));
this.DataContext = this;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
这是 XAML 的代码:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid>
<ListBox ItemsSource="{Binding ObjectList}">
</ListBox>
</Grid>
</Window>
这是数据库的代码:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace WpfApp1.Database
{
public class AppDBContext : DbContext
{
public virtual DbSet<TestModel> TestTable { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string Path = System.AppDomain.CurrentDomain.BaseDirectory + @"\database.db";
if (File.Exists(Path))
{
optionsBuilder.UseSqlite("Data Source=" + Path);
}
}
}
}
这是数据库模型的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace WpfApp1.Database
{
public class TestModel
{
[Key]
public string id { get; set; }
public string name { get; set; }
}
}
PS:我把database.db和我的程序文件放在同一个文件夹里。
如果我在没有Produce Single File 的情况下调试或发布程序,一切正常。
它有什么问题?我该如何解决这个问题?谢谢。
【问题讨论】:
-
您是否调试过您的程序并检查过在您创建新的 DbContext 时是否会调用 OnConfiguring?我希望它不会,并且您必须在创建 DbContext 时为您的 DbContext 提供类似 DbContextOptions 的东西。您应该阅读有关如何创建 DbContext 的文档。
标签: c# wpf entity-framework entity-framework-core