1、新增 App.Config 檔案,並且配置資料庫的相對位置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings > <!--|DataDirectory| 表示相對目錄 --> <add name="SqliteConnection" connectionString="Data Source=.\Resources\Data\text.db;" providerName="system.Data.SQLite"/> </connectionStrings> </configuration>
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、生成 資料庫