首页 > 代码库 > Entity Framwork系列之Model First

Entity Framwork系列之Model First

第一步 新建数据库

新建数据库TestDB2

第二步 ADO.NET实体数据模型

新建空的ADO.NET实体数据模型

新增实体(表)和类型(字段)

右键TestModel.edmx界面点击“根据模型生成数据库”,执行生成的TestModel.edmx.sql文件中的SQL语句。

第三步 增删改查

using System;using System.Data;using System.Linq;using System.Windows.Forms;namespace EFDEMO3{    public partial class Form1 : Form    {        TestModelContainer entity = new TestModelContainer();        public Form1()        {            InitializeComponent();        }        /// <summary>        /// 新增        /// </summary>        private void Add()        {            T_Action model = new T_Action()            {                Name = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")            };            entity.T_Action.Add(model);            entity.SaveChanges();            Query();        }        /// <summary>        /// 删除        /// </summary>        private void Delete()        {            if (listBox1.SelectedItem == null)            {                return;            }            int id = Convert.ToInt32(listBox1.SelectedItem.ToString().Split(-)[0]);            T_Action model = entity.T_Action.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]);            T_Action model = entity.T_Action.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 = entity.T_Action;            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 Framwork系列之Model First