目录
前文已经说过.NET Framework4.8 控制台应用通过EF访问已经建立的和新建的数据库。
本文想说的是,.NET Framework4.8 Windows窗体应用通过EF访问新建数据库,这里的数据据库要根据事先编写好的EF模型、和数据库上下文,经过一番操作,移植(Migrations)出来的。这个数据库在“工具、连接到数据库”是看不到这个数据库的连接的。
一、 操作步骤
-
新建VS.NET Framework4.8 Windows窗体应用;
- 安装适合版本的EF程序包,3.1.32.0;
- 编写EF模型和数据库上下文,文件录入格式是添加新的类;
- 移植(Migrations)数据库,资源管理器里生成Migrations夹;
- 编写应用程序文件Form1.cs;
- 运行;
步骤1和步骤2作者以前的文章都讲过,不再重复叙述。
二、编写EF模型和数据库上下文
添加→新建项目→类,复制粘贴以下全文,一定要保证所有.cs文件在同一片空间下(namespace)。
//编写EF模型和数据库上下文
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace _10_14
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> 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<Post> 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\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
Unable to resolve startup project ''.
Using project '10_14' as the startup project.
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> Update-Database
Unable to resolve startup project ''.
Using project '10_14' as the startup project.
Build started...
Build succeeded.
Applying migration '20231115063747_MyMigration'.
Failed executing DbCommand (4ms) [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.
在 Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlConnection.cs:行号 2117
在 Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:行号 1572
在 Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\TdsParser.cs:行号 0
在 Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:行号 3752
在 Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:行号 1986
在 Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery() 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:行号 1439
在 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
在 Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
在 Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
在 Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:f67e88b9-c5de-46e3-9746-9440f3bf2eee
Error Number:2714,State:6,Class:16
There is already an object named 'Blogs' in the database.
PM>
我的电脑中在其他项目中已经移植生成过同样的数据库,因此在数据库更新时提示并警告,忽略就好了,不影响本项目的调试和运行的。
四、编写应用程序
//.NET Framework4.8窗体应用通过EF访问新建数据库
//追加、删除数据库记录
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace _10_14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 初始化Form1
/// 初始化表格,显示数据表
/// </summary>
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "追加";
button2.Text = "删除";
label1.Text = "追加的Url:";
label2.Text = "删除的ID:";
button1.Size = new Size(40, 23);
button2.Size = new Size(40, 23);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
using (var db = new BloggingContext())
{
dataGridView1.DataSource = db.Blogs.ToList();
}
}
/// <summary>
/// 追加Add()
/// 无论ID是否连续,都在数据库末尾追加新纪录
/// </summary>
#region 追加
private void Button1_Click(object sender, EventArgs e)
{
using (var db = new BloggingContext())
{
if (textBox1.Text != "")
{
db.Blogs.Add(new Blog { Url = textBox1.Text.Trim().ToString() }); //追加记录
db.SaveChanges();
dataGridView1.DataSource = db.Blogs.ToList();
}
else
{
db.Blogs.Add(new Blog { Url = "http://www.hao123.com/" }); //追加记录
db.SaveChanges();
dataGridView1.DataSource = db.Blogs.ToList();
}
}
}
#endregion 追加
/// <summary>
/// 删除Remove()
/// </summary>
#region 删除记录
private void Button2_Click(object sender, EventArgs e)
{
using (var db = new BloggingContext())
{
db.Blogs.Remove(new Blog { BlogId = Convert.ToInt32(textBox2.Text.Trim()) }); //删除记录按ID
db.SaveChanges();
dataGridView1.DataSource = db.Blogs.ToList();
}
}
#endregion 删除记录
}
}
五、生成效果
追加:http://www.hao123.com
追加:http://www.taobao.com
删除ID=2的记录