时间:2017-03-09
系列文章:
EF-ModelFirst实现过程
EF-CodeFirst实现过程(详细)+数据库迁移
建议学习路径 DBFirst->ModelFirst->CodeFirst
思路:通过SQL Server 2014 Management Studio设计好数据库之后,根据数据库生成实体和上下文。
1,设计数据库
新建数据库以及数据表
设置主键,并将主键设置为标识列(主键自增)。


2,新建项目
文件->新建->项目->控制台应用程序

项目->添加->数据->ADO.NET实体数据模型。

来自数据库的EF设计器

新建连接
服务器名的获取:



此时项目文件为:

在Model1.Context.cs下找到上下文,并Ctrl+C

到Program.cs下编写代码实现EF增删改查
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF_DBFirst_Demo
{
class Program
{
static void Main(string[] args)
{
//使用using的原因:因为连接数据库是非常占用资源的,所以我们要及时释放,using的作用就是在代码块执行完毕后立即释放资源,不需等待CLR的资源回收机制处理。
//1.实例化上下文对象
using (EF_DBFirstDemoEntities dbContext=new EF_DBFirstDemoEntities())
{
//2.实例化对象实例
Customer customer_A = new Customer();
customer_A.CreateTime=DateTime.Now;
customer_A.CreateBy = "Fnatic";
customer_A.CustomerName = "FutaoSmile";
//不需要指定id,因为id是自增的,所以数据库会自动赋值,我们在这边赋值了也是没用的。
//3.告诉EF我们要对哪张表进行什么样的操作
dbContext.Customer.Add(customer_A);
//4.将数据同步到数据库
dbContext.SaveChanges();
}
//修改数据的第二种方法。(第一种方法请参见下面给出的链接)
1.实例化上下文对象
using (EF_DBFirstDemoEntities dbContext=new EF_DBFirstDemoEntities())
{
//2.根据ID从数据库获取对应的数据并赋值给一个实例化的对象
Customer customer= dbContext.Customer.FirstOrDefault(u => u.CustomerID==2);
//或 Customer customer = dbContext.Customer.Find(2);
//3.更改需要更改的值
customer.CreateBy = "Admin";
customer.CreateTime = DateTime.Now;
//4.将数据同步到数据库
dbContext.SaveChanges();
}
}
}
增删改查的实现请参见我的另一篇文章:http://www.jianshu.com/nb/10166743
谢谢O(∩_∩)O~</br>
网友评论