【EF core】App.config 的配置
1、添加 App.Config 文件,并且配置数据库的相对位置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings > <!--点号 表示相对目录 --> <add name="SqliteConnection" connectionString="Data Source=.\Resources\Data\text.db;" providerName="system.Data.SQLite"/> </connectionStrings> </configuration>
当出现这种错误,是路径未生成生成, Debug问价夹 下Resources\Data 下是否存在 这两个文件夹。
2、EF core 的DbContext中配置如下:
using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IndividualQAlibrary.MVVM.Models { internal class TestDataContext:DbContext { public DbSet<Programming> Programmings { get; set; } string connectionString; public TestDataContext() { connectionString = ConfigurationManager.ConnectionStrings["SqliteConnection"].ConnectionString; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); var builder = new SqliteConnectionStringBuilder(connectionString); optionsBuilder.UseSqlite(connectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } }
3、实体
using System; using System.Collections.Generic; namespace IndividualQAlibrary.MVVM.Models; public partial class Programming { public int? Id { get; set; } public string? Questiontype { get; set; } public string? Content { get; set; } public int? Numberoferrors { get; set; } public string? Answer { get; set; } public string? Classify { get; set; } public string? Creationtime { get; set; } public string? Remark { get; set; } }
4、wpf 窗体代码
using IndividualQAlibrary.MVVM.Models; using System; using System.Collections.Generic; 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.Shapes; namespace IndividualQAlibrary.MVVM.Views { /// <summary> /// QAlibraryView.xaml 的交互逻辑 /// </summary> public partial class QAlibraryView : Window { public QAlibraryView() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { TestDataContext test = new TestDataContext(); test.Database.EnsureCreated(); } } }
点击按钮后生成数据库
5、生成 数据库
编程是个人爱好