标签:
使用管理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; } } }
<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(); } } }
标签:
原文地址:http://www.cnblogs.com/cmhunter/p/4224951.html