1. 創建 EFCoreApp項目
使用 VS2019 新建 net core App 空項目, 其項目配置如下:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
2. 安裝 EF Core
打開 VS 的 工具 -> NuGet 包管理器, 使用界面或者命令行安裝 EF Core
在搜索欄 搜索 ef core
, 選擇 ef core 安裝:
接收安裝許可:
接下來安裝 sqlite, 選擇 ef core.sqlite 進行安裝並接受許可.
查看項目文件可看到已經安裝了兩個包:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.4" />
</ItemGroup>
</Project>
3. 使用EF Core
EF Core中一個很重要的類是 : DbContext
, 我們需要繼承此類 編寫數據庫操作的代碼.
namespace EFCoreApp.Data
{
public class AppDbContext : DbContext
{
public DbSet<KeyValueTable> KeyValues { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlite("Data Source=App.db");
}
}
[Table("KeyValue")]
public class KeyValueTable
{
[Key]
public string Id{ get; set; }
[Column("key")]
public string Key { get; set; }
[Column("value")]
public string Value { get; set; }
}
}
這裏我們繼承了 DbContext 並連接數據庫 App.db
, 創建一個數據表: KeyValue
.
然後需要在 App 啓動回調中 創建數據庫:
namespace EFCoreApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void App_OnStartup(object sender, StartupEventArgs e)
{
AppDbContext dbContext = new AppDbContext();
dbContext.Database.EnsureCreated();
}
private void App_OnExit(object sender, ExitEventArgs e)
{
}
}
}
啓動 運行後我們可以看到 創建的 數據庫文件: App.db
, 打開數據庫可以看到創建的數據表.
至此, EF Core 的安裝使用第一部分到此結束. 下一部分看看 如何進行 數據庫的常用操作: 增 改 刪 查
4 項目地址
本項目代碼地址在此: DevWiki/EFCoreApp