• C#中.NET Framework4.8 Windows窗体应用通过EF访问新建数据库


    目录

    一、 操作步骤

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

    三、 移植(Migrations)数据库

    四、编写应用程序

    五、生成效果


            前文已经说过.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)。

    1. //编写EF模型和数据库上下文
    2. using Microsoft.EntityFrameworkCore;
    3. using System.Collections.Generic;
    4. namespace _10_14
    5. {
    6. public class BloggingContext : DbContext
    7. {
    8. public DbSet Blogs { get; set; }
    9. public DbSet Posts { get; set; }
    10. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    11. {
    12. optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
    13. }
    14. }
    15. public class Blog
    16. {
    17. public int BlogId { get; set; }
    18. public string Url { get; set; }
    19. public List Posts { get; set; }
    20. }
    21. public class Post
    22. {
    23. public int PostId { get; set; }
    24. public string Title { get; set; }
    25. public string Content { get; set; }
    26. public int BlogId { get; set; }
    27. public Blog Blog { get; set; }
    28. }
    29. }

    三、 移植(Migrations)数据库

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

    1. //移植并新建数据库
    2. PM> Import-Module C:\Users\YCZN_MT\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.32\tools\EntityFrameworkCore.psd1
    3. 模块“EntityFrameworkCore”中的某些导入命令的名称包含未批准的动词,这些动词可能导致这些命令名不易被发现。若要查找具有未批准的动词的命令,请使用 Verbose 参数再次运行 Import-Module 命令。有关批准的动词列表,请键入 Get-Verb。
    4. PM> Get-Verb
    5. Verb Group
    6. ---- -----
    7. Add Common
    8. Clear Common
    9. Close Common
    10. Copy Common
    11. Enter Common
    12. Exit Common
    13. Find Common
    14. Format Common
    15. Get Common
    16. Hide Common
    17. Join Common
    18. Lock Common
    19. Move Common
    20. New Common
    21. Open Common
    22. Optimize Common
    23. Pop Common
    24. Push Common
    25. Redo Common
    26. Remove Common
    27. Rename Common
    28. Reset Common
    29. Resize Common
    30. Search Common
    31. Select Common
    32. Set Common
    33. Show Common
    34. Skip Common
    35. Split Common
    36. Step Common
    37. Switch Common
    38. Undo Common
    39. Unlock Common
    40. Watch Common
    41. Backup Data
    42. Checkpoint Data
    43. Compare Data
    44. Compress Data
    45. Convert Data
    46. ConvertFrom Data
    47. ConvertTo Data
    48. Dismount Data
    49. Edit Data
    50. Expand Data
    51. Export Data
    52. Group Data
    53. Import Data
    54. Initialize Data
    55. Limit Data
    56. Merge Data
    57. Mount Data
    58. Out Data
    59. Publish Data
    60. Restore Data
    61. Save Data
    62. Sync Data
    63. Unpublish Data
    64. Update Data
    65. Approve Lifecycle
    66. Assert Lifecycle
    67. Complete Lifecycle
    68. Confirm Lifecycle
    69. Deny Lifecycle
    70. Disable Lifecycle
    71. Enable Lifecycle
    72. Install Lifecycle
    73. Invoke Lifecycle
    74. Register Lifecycle
    75. Request Lifecycle
    76. Restart Lifecycle
    77. Resume Lifecycle
    78. Start Lifecycle
    79. Stop Lifecycle
    80. Submit Lifecycle
    81. Suspend Lifecycle
    82. Uninstall Lifecycle
    83. Unregister Lifecycle
    84. Wait Lifecycle
    85. Debug Diagnostic
    86. Measure Diagnostic
    87. Ping Diagnostic
    88. Repair Diagnostic
    89. Resolve Diagnostic
    90. Test Diagnostic
    91. Trace Diagnostic
    92. Connect Communications
    93. Disconnect Communications
    94. Read Communications
    95. Receive Communications
    96. Send Communications
    97. Write Communications
    98. Block Security
    99. Grant Security
    100. Protect Security
    101. Revoke Security
    102. Unblock Security
    103. Unprotect Security
    104. Use Other
    105. PM> Add-Migration
    106. 位于命令管道位置 1 的 cmdlet Add-Migration
    107. 请为以下参数提供值:
    108. Name: MyMigration
    109. Unable to resolve startup project ''.
    110. Using project '10_14' as the startup project.
    111. Build started...
    112. Build succeeded.
    113. To undo this action, use Remove-Migration.
    114. PM> Update-Database
    115. Unable to resolve startup project ''.
    116. Using project '10_14' as the startup project.
    117. Build started...
    118. Build succeeded.
    119. Applying migration '20231115063747_MyMigration'.
    120. Failed executing DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
    121. CREATE TABLE [Blogs] (
    122. [BlogId] int NOT NULL IDENTITY,
    123. [Url] nvarchar(max) NULL,
    124. CONSTRAINT [PK_Blogs] PRIMARY KEY ([BlogId])
    125. );
    126. Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Blogs' in the database.
    127. 在 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
    128. 在 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
    129. 在 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
    130. 在 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
    131. 在 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
    132. 在 Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery() 位置 H:\tsaagent4\_work\2\s\src\Microsoft.Data.SqlClient\netfx\src\Microsoft\Data\SqlClient\SqlCommand.cs:行号 1439
    133. 在 Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
    134. 在 Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
    135. 在 Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
    136. 在 Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
    137. 在 Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
    138. 在 Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
    139. ClientConnectionId:f67e88b9-c5de-46e3-9746-9440f3bf2eee
    140. Error Number:2714,State:6,Class:16
    141. There is already an object named 'Blogs' in the database.
    142. PM>

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

    四、编写应用程序

    1. //.NET Framework4.8窗体应用通过EF访问新建数据库
    2. //追加、删除数据库记录
    3. using System;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Linq;
    7. using System.Windows.Forms;
    8. namespace _10_14
    9. {
    10. public partial class Form1 : Form
    11. {
    12. public Form1()
    13. {
    14. InitializeComponent();
    15. }
    16. ///
    17. /// 初始化Form1
    18. /// 初始化表格,显示数据表
    19. ///
    20. private void Form1_Load(object sender, EventArgs e)
    21. {
    22. button1.Text = "追加";
    23. button2.Text = "删除";
    24. label1.Text = "追加的Url:";
    25. label2.Text = "删除的ID:";
    26. button1.Size = new Size(40, 23);
    27. button2.Size = new Size(40, 23);
    28. dataGridView1.AllowUserToAddRows = false;
    29. dataGridView1.AllowUserToDeleteRows = false;
    30. dataGridView1.AllowUserToResizeColumns = false;
    31. dataGridView1.AllowUserToResizeRows = false;
    32. dataGridView1.RowHeadersVisible = false;
    33. dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
    34. using (var db = new BloggingContext())
    35. {
    36. dataGridView1.DataSource = db.Blogs.ToList();
    37. }
    38. }
    39. ///
    40. /// 追加Add()
    41. /// 无论ID是否连续,都在数据库末尾追加新纪录
    42. ///
    43. #region 追加
    44. private void Button1_Click(object sender, EventArgs e)
    45. {
    46. using (var db = new BloggingContext())
    47. {
    48. if (textBox1.Text != "")
    49. {
    50. db.Blogs.Add(new Blog { Url = textBox1.Text.Trim().ToString() }); //追加记录
    51. db.SaveChanges();
    52. dataGridView1.DataSource = db.Blogs.ToList();
    53. }
    54. else
    55. {
    56. db.Blogs.Add(new Blog { Url = "http://www.hao123.com/" }); //追加记录
    57. db.SaveChanges();
    58. dataGridView1.DataSource = db.Blogs.ToList();
    59. }
    60. }
    61. }
    62. #endregion 追加
    63. ///
    64. /// 删除Remove()
    65. ///
    66. #region 删除记录
    67. private void Button2_Click(object sender, EventArgs e)
    68. {
    69. using (var db = new BloggingContext())
    70. {
    71. db.Blogs.Remove(new Blog { BlogId = Convert.ToInt32(textBox2.Text.Trim()) }); //删除记录按ID
    72. db.SaveChanges();
    73. dataGridView1.DataSource = db.Blogs.ToList();
    74. }
    75. }
    76. #endregion 删除记录
    77. }
    78. }

    五、生成效果

     

             追加:http://www.hao123.com

             追加:http://www.taobao.com

            删除ID=2的记录 

  • 相关阅读:
    小皮面板为什么还是打不开?
    springboot-统一打印内容
    Nginx(五)
    4.0、软件测试——等价类划分以及练习
    数据湖(二):什么是Hudi
    《SprigBoot篇》09.Spring Data JPA简介与SpringBoot整合超详细教学
    NFT 的 10 种实际用途
    渗透测试-xml注入以及xxe漏洞
    DP - OOD - ISP
    【csapp lab】lab2_bomblab
  • 原文地址:https://blog.csdn.net/wenchm/article/details/134418541