第一步:安装Entity Framework6.0
使用管理NuGet程序包界面安装EntityFramework
第二步:新建实体类
using System.ComponentModel.DataAnnotations; namespace EFDemo4 { public class User { [Key] public int Id { get; set; } public string Name { get; set; } } }
第三步:新建实体上下文类
using System.Data.Entity; namespace EFDemo4 { public class TestDBContext: DbContext { public TestDBContext() : base("name=TestDB3") { } public DbSet<User> Users { get; set; } } }
App.config文件中的数据库连接字符串
<connectionStrings>
<add name="TestDB3" providerName="System.Data.SqlClient" connectionString="Data Source=.\CMDB;Initial Catalog=TestDB3;Integrated Security=SSPI;" />
</connectionStrings>
第四步:增删改查
在执行数据库操作之后,数据库对象会自动创建
using System; using System.Data.Entity; using System.Linq; using System.Windows.Forms; namespace EFDemo4 { public partial class Form1 : Form { TestDBContext entity = new TestDBContext(); public Form1() { InitializeComponent(); } /// <summary> /// 新增 /// </summary> private void Add() { User model = new User() { Name = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }; entity.Users.Add(model); entity.SaveChanges(); Query(); } /// <summary> /// 删除 /// </summary> private void Delete() { if (listBox1.SelectedItem == null) { return; } int id = Convert.ToInt32(listBox1.SelectedItem.ToString().Split(‘-‘)[0]); User model = entity.Users.Where(a => a.Id == id).FirstOrDefault(); if (model != null) { entity.Entry(model).State = EntityState.Deleted; entity.SaveChanges(); Query(); } } /// <summary> /// 修改 /// </summary> private void Edit() { if (listBox1.SelectedItem == null) { return; } int id = Convert.ToInt32(listBox1.SelectedItem.ToString().Split(‘-‘)[0]); User model = entity.Users.Where(a => a.Id == id).FirstOrDefault(); if (model != null) { model.Name = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); entity.Entry(model).State = EntityState.Modified; entity.SaveChanges(); Query(); } } /// <summary> /// 查询 /// </summary> private void Query() { listBox1.Items.Clear(); var expr = from p in entity.Users select p; foreach (var item in expr) { listBox1.Items.Add(string.Format("{0}-{1}", item.Id, item.Name)); } } private void toolStripButton1_Click(object sender, EventArgs e) { Add(); } private void toolStripButton4_Click(object sender, EventArgs e) { Edit(); } private void toolStripButton3_Click(object sender, EventArgs e) { Delete(); } private void toolStripButton2_Click(object sender, EventArgs e) { Query(); } } }
时间: 2024-11-19 19:06:58