首页 > 代码库 > Entity Framework系列之Code First
Entity Framework系列之Code First
第一步:安装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>
<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(); } }}
Entity Framework系列之Code First
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。