目录

一、 操作步骤

二、编写EF模型和数据库上下文

三、 移植(Migrations)数据库

四、编写应用程序并运行


        前文已经说过.NET Framework4.8 控制台应用通过EF访问已经建立的数据库,这里说的已经建立的数据库指的是已经建立的SQLServer那样的数据库或VS 的本地数据库(localdb) \MSSQLLocalDB。这些数据库能够通过SSMS建立连接或在VS上建立本地的数据库连接,是可以操作的、可以看得见的。

        本文想说的是,.NET Framework4.8 控制台应用通过EF访问新建数据库,这里的数据据库要根据事先编写好的EF模型、经过一番操作,移植(Migrations)出来的。这个数据库是看不到这个数据库的连接的。

一、 操作步骤

  1. 新建VS.NET Framework4.8 控制台应用;
  2. 安装适合版本的EF程序包,3.1.32.0;
  3. 编写EF模型和数据库上下文,文件录入格式是添加新的类;
  4. 移植(Migrations)数据库,资源管理器里生成Migrations夹;
  5. 编写应用程序文件Program.cs;
  6. 运行;

        步骤1和步骤2作者以前的文章都讲过,不再重复叙述。

二、编写EF模型和数据库上下文

         添加→新建项目→类,复制粘贴以下全文,一定要保证所有.cs文件在同一片空间下(namespace)。

//EF模型数据库上下文
using Microsoft.EntityFrameworkCore.Migrations;

namespace _10_10.Migrations
{
    public partial class MyMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Blogs",
                columns: table => new
                {
                    BlogId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Url = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Blogs", x => x.BlogId);
                });

            migrationBuilder.CreateTable(
                name: "Posts",
                columns: table => new
                {
                    PostId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Title = table.Column<string>(nullable: true),
                    Content = table.Column<string>(nullable: true),
                    BlogId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Posts", x => x.PostId);
                    table.ForeignKey(
                        name: "FK_Posts_Blogs_BlogId",
                        column: x => x.BlogId,
                        principalTable: "Blogs",
                        principalColumn: "BlogId",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Posts_BlogId",
                table: "Posts",
                column: "BlogId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Posts");

            migrationBuilder.DropTable(
                name: "Blogs");
        }
    }
}

三、 移植(Migrations)数据库

        如果Add-Migration出现警告而失败,就按下属过程操作。

//移植(Migrations)数据库

PM> Import-Module C:\Users\pc\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.32\tools\EntityFrameworkCore.psd1
模块“EntityFrameworkCore”中的某些导入命令的名称包含未批准的动词,这些动词可能导致这些命令名不易被发现。若要查找具有未批准的动词的命令,请使用 Verbose 参数再次运行 Import-Module 命令。有关批准的动词列表,请键入 Get-Verb。
PM> Get-Verb

Verb        Group         
----        -----         
Add         Common        
Clear       Common        
Close       Common        
Copy        Common        
Enter       Common        
Exit        Common        
Find        Common        
Format      Common        
Get         Common        
Hide        Common        
Join        Common        
Lock        Common        
Move        Common        
New         Common        
Open        Common        
Optimize    Common        
Pop         Common        
Push        Common        
Redo        Common        
Remove      Common        
Rename      Common        
Reset       Common        
Resize      Common        
Search      Common        
Select      Common        
Set         Common        
Show        Common        
Skip        Common        
Split       Common        
Step        Common        
Switch      Common        
Undo        Common        
Unlock      Common        
Watch       Common        
Backup      Data          
Checkpoint  Data          
Compare     Data          
Compress    Data          
Convert     Data          
ConvertFrom Data          
ConvertTo   Data          
Dismount    Data          
Edit        Data          
Expand      Data          
Export      Data          
Group       Data          
Import      Data          
Initialize  Data          
Limit       Data          
Merge       Data          
Mount       Data          
Out         Data          
Publish     Data          
Restore     Data          
Save        Data          
Sync        Data          
Unpublish   Data          
Update      Data          
Approve     Lifecycle     
Assert      Lifecycle     
Complete    Lifecycle     
Confirm     Lifecycle     
Deny        Lifecycle     
Disable     Lifecycle     
Enable      Lifecycle     
Install     Lifecycle     
Invoke      Lifecycle     
Register    Lifecycle     
Request     Lifecycle     
Restart     Lifecycle     
Resume      Lifecycle     
Start       Lifecycle     
Stop        Lifecycle     
Submit      Lifecycle     
Suspend     Lifecycle     
Uninstall   Lifecycle     
Unregister  Lifecycle     
Wait        Lifecycle     
Debug       Diagnostic    
Measure     Diagnostic    
Ping        Diagnostic    
Repair      Diagnostic    
Resolve     Diagnostic    
Test        Diagnostic    
Trace       Diagnostic    
Connect     Communications
Disconnect  Communications
Read        Communications
Receive     Communications
Send        Communications
Write       Communications
Block       Security      
Grant       Security      
Protect     Security      
Revoke      Security      
Unblock     Security      
Unprotect   Security      
Use         Other         


PM> Add-Migration
位于命令管道位置 1 的 cmdlet Add-Migration
请为以下参数提供值:
Name: MyMigration
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Applying migration '20231114142239_MyMigration'.
Done.
PM> 

四、编写应用程序并运行

//.NET Framework4.8控制台应用通过EF访问新建数据库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10_10
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                var count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);

                Console.WriteLine();
                Console.WriteLine("All blogs in database:");
                foreach (var blog in db.Blogs)
                {
                    Console.WriteLine(" - {0}", blog.Url);
                }
            }
        }
    }
}//运行结果:
/*
 1 records saved to database

All blogs in database:
 - http://blogs.msdn.com/adonet
请按任意键继续. . .*/
11-15 03:57