1. 程式人生 > >EntityFramework Core筆記:入門(1)

EntityFramework Core筆記:入門(1)

tool power arc 2.3 isp IE clas scope color

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; } } }
Role.cs

  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 NSET 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管理員

EntityFramework Core筆記:入門(1)