第一步:安装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; } } }
更新数据结构
当我们的数据结构变化了后,就会出现数据模型和数据库不一致的情况。此时运行则会出现如下异常:
未经处理的异常: System.InvalidOperationException: The model backing the 'BloggingContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
解决方案:
1、Code First Migrations(数据迁移)
2、在程序启动前增加一行代码:System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TestDBContext>()); 要注意的事,该方法将重建整个数据库,因此原来的数据将会丢失。
using System; using System.Data.Entity; using System.Windows.Forms; namespace EFDemo4 { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { #if DEBUG System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TestDBContext>()); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
第三步:新建实体上下文类
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>
<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(); } } }