目录
前文作者发布了在.NET Framework4.8 控制台应用中通过EF访问已有数据库,事实上在.NET Framework4.8 Windows窗体应用中通过EF访问已有数据库也是一样的。操作方法基本一样,数据库EF模型和上下文都是自动生成的,在这里不再重复叙述,只把应用部分、窗体设计、生成效果分享出来。
设计有一个窗体,dataGridView1显示数据库的数据表blog,textBox1的文本是要追加记录的网址,button1是追加按钮。textBox2的文本是要删除记录的ID,button2是删除按钮。
- //.NET Framework4.8窗体应用通过EF访问已有数据库
- //追加、删除数据库记录
- using System;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Windows.Forms;
-
- namespace _10_7
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- ///
- /// 初始化Form1
- /// 初始化表格,显示数据表
- ///
- 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.Blog.ToList();
- }
- }
-
- ///
- /// 追加Add()
- /// 无论ID是否连续,都在数据库末尾追加新纪录
- ///
- #region 追加
- private void Button1_Click(object sender, EventArgs e)
- {
- using (var db = new BloggingContext())
- {
- if (textBox1.Text != "")
- {
- db.Blog.Add(new Blog { Url = textBox1.Text.Trim().ToString() }); //追加记录
- db.SaveChanges();
- dataGridView1.DataSource = db.Blog.ToList();
- }
- else
- {
- db.Blog.Add(new Blog { Url = "http://www.hao123.com/" }); //追加记录
- db.SaveChanges();
- dataGridView1.DataSource = db.Blog.ToList();
- }
- }
- }
- #endregion 追加
-
- ///
- /// 删除Remove()
- ///
- #region 删除记录
- private void Button2_Click(object sender, EventArgs e)
- {
- using (var db = new BloggingContext())
- {
- db.Blog.Remove(new Blog { BlogId = Convert.ToInt32(textBox2.Text.Trim()) }); //删除记录按ID
- db.SaveChanges();
- dataGridView1.DataSource = db.Blog.ToList();
- }
- }
- #endregion 删除记录
- }
- }