1. 安裝執行環境
EntityFramework Core執行環境,安裝NuGget包:
//Sql Server Database Provider PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
//提供Add-Migration,Update-Database等Powershell命令 PM> Install-Package Microsoft.EntityFrameworkCore.Tools
2. 控制檯程式
2.1 基礎程式碼
實體類:Role.cs
using System; using System.Collections.Generic; using System.Text; namespace Libing.App.Models.Entities { public class Role { public int RoleID { get; set; } public string RoleName { get; set; } } }
DbContext.cs
using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; using Libing.App.Models.Entities;namespace Libing.App.Models { public class LibingContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // 資料庫連線 optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=Libing;Integrated Security=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Role> Roles { get; set; } } }
2.2 生成表結構
PM> Add-Migration InitialCreate
PM> Update-Database
2.3 執行程式碼
using System; using Libing.App.Models; using Libing.App.Models.Entities; namespace Libing.App { class Program { static void Main(string[] args) { using (var context = new LibingContext()) { var role = new Role { RoleName = "管理員" }; context.Roles.Add(role); context.SaveChanges(); } } } }
執行的SQL語句:
exec sp_executesql N'SET NOCOUNT ON; INSERT INTO [dbo].[Role] ([RoleName]) VALUES (@p0); SELECT [RoleID] FROM [dbo].[Role] WHERE @@ROWCOUNT = 1 AND [RoleID] = scope_identity(); ',N'@p0 nvarchar(100)',@p0=N'管理員'