C#中.NET 6.0 控制台应用通过EF访问新建数据库

目录

一、 操作步骤

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

三、 移植(Migrations)数据库

四、编写应用程序并运行


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

一、 操作步骤

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

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

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

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

//数据库上下文BloggingContext和EF模型
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace _10_13
{
    public class BloggingContext : DbContext
    {
        public DbSet? Blogs { get; set; }
        public DbSet? Posts { get; set; }
        /// 
        /// 数据库连接字符串,数据库的名字可改可不改,因为移植生成的数据库是虚拟的
        /// 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
        }
    }

    public class Blog
    {
        public int? BlogId { get; set; }
        public string? Url { get; set; }

        public List? Posts { get; set; }
    }

    public class Post
    {
        public int? PostId { get; set; }
        public string? Title { get; set; }
        public string? Content { get; set; }

        public int? BlogId { get; set; }
        public Blog? Blog { get; set; }
    }
}

三、 移植(Migrations)数据库

         如果Add-Migration出现警告而失败,就按下述过程操作。也可以,无论是否因警告而失败,都可以直接按下述操作。

//新建数据库
PM> Import-Module C:\Users\YCZN_MT\.nuget\packages\microsoft.entityframeworkcore.tools\7.0.14\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: MyMigratin
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Build started...
Build succeeded.
Applying migration '20231115035211_MyMigratin'.
Failed executing DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Blogs] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NULL,
    CONSTRAINT [PK_Blogs] PRIMARY KEY ([BlogId])
);
Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Blogs' in the database.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
   at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:217d3687-28a0-4467-8dfd-09e430245bc2
Error Number:2714,State:6,Class:16
There is already an object named 'Blogs' in the database.
PM> 

        我的电脑中在其他项目中已经移植生成过同样的数据库,因此在数据库更新时提示并警告,忽略就好了,不影响本项目的调试和运行的。

四、编写应用程序并运行

//.NET 6.0控制台应用EF访问新建数据库
//每运行一次增加一条记录
//同一台电脑其他项目移植过相同的项目的话,在Update-Database时会
//发生可以忽略的红色警告,不影响向调试运行。只要自动生成移植就可以
using System;

namespace _10_13
{
    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
 - http://blogs.msdn.com/adonet

C:\Users\YCZN_MT\Desktop\测试1\10_13[.NET6.0控制台 EF新建]\10_13\bin\Debug\net6.0\10_13.exe (进程 12848)已退出,代码为 0。
按任意键关闭此窗口. . .*/

        第一条记录是同一台电脑的另外的工程生成的数据库记录,第二条记录是本项目执行1次后生成的,如果关闭执行后,重新执行,每执行一次,添加1条记录。

你可能感兴趣的:(数据库,c#,.net)