EF(EntityFrameWork) ORM(对象关系映射框架/数据持久化框架),根据实体对象操作数据表中数据的一种面向对象的操作框架,底层也是调用ADO.NET

ASP.NET MVC 项目会自动导入MVC程序集,因为默认.NET环境(GAC)中没有这个程序集

1: EF数据上下文 继承于 DbContext ; DBQuery<T> ,支持延迟加载:只有当使用到数据的时候,才去查询数据库; 主要成员:表映射的实体集合 Set<T>,Entry<T>()

  context.Model -->Dbset<Model>

  context.set<Model>() -->Dbset<Model>

  //使用状态版的时候,执行修改/删除的时候必须指定主键。

2: EF中会为每个 管理的 实体对象 创建一个代理包装类对象,其中会跟踪 实体对象 的状态和每个属性的状态;

3: [EF对象管理容器]每个通过EF数据上下文操作的实体对象,都需要存在上下文的容器中,一旦通过上下文的某个方法操作了实体对象后,那么上下文就会给它加一个状态标识。

但调用上下文的SaveChanges方法的时候,上下文就会遍历容器中的所有对象,并检查他们的状态标识,并依照标识的值进行相应的增删改查sql操作

一、通常使用EF更新的方式,先查询出要修改的数据,然后再修改新的值;实体对象被修改的属性 在 代理包装类对象里 的对应属性状态会被修改记录下修改状态,

等到调用SaveChanges时,EF会遍历其管理的每个实体对象,并根据其 包装类对象 的状态,生成增删改查sql语句并执行;

此例中修改操作,会生成 修改的sql语句(注意:此处只为修改过的属性生成sql语句),最后执行。

 create database MyFirstEF
on primary
(
name='MyFirstEF.mdf',
--修改为自己电脑上SQL DB路径
filename='E:\ProgramMSSQLServerDB\MyFirstEF.mdf',
size=5mb,
maxsize=100mb,
filegrowth=10%
)
log on
(
name='MyFirstEF_log.ldf',
--修改为自己电脑上SQL DB路径
filename='E:\ProgramMSSQLServerDB\MyFirstEF_log.ldf',
size=2mb,
maxsize=100mb,
filegrowth=5mb
)
go use MyFirstEF
go create table CustomerInfo
(
id int identity(1,1) primary key,
customerName nvarchar(100) not null,
customerDate datetime
)
go insert into CustomerInfo values('aaaaa',getdate())
go select * from CustomerInfo
go create table OrderInfo
(
id int identity(1,1) primary key,
orderName nvarchar(100),
customerId int
)
go alter table OrderInfo
add constraint FK_OrderInfo_CustomerInfo
foreign key(customerId) references CustomerInfo(id)
on delete cascade
on update cascade go select * from CustomerInfo
select * from OrderInfo

create SQL

//EF context 对象
MyFirstEFEntities context = new MyFirstEFEntities(); //update
//1:先查询要修改的原数据
CustomerInfo customer = context.CustomerInfoes.Find();
//2:设置修改后的值
customer.customerDate = DateTime.Now;
//3:更新到数据库
context.SaveChanges();

二、为避免先查询数据库,可以直接将 被修改的实体对象 添加到 EF中管理(此时为附加状态Attached),并手动设置其为未修改状态(Unchanged),

同时设置被修改的实体对象的包装类对象 对应属性为修改状态。

//EF context 对象
DbContext contextState = new MyFirstEFEntities(); //update
CustomerInfo customerState = new CustomerInfo();
customerState.id = ;
customerState.customerDate = DateTime.Now;
customerState.customerName = "bbb"; //1: 标记当前对象,必须把必填字段都填写,否则会报错:System.Data.Entity.Validation.DbEntityValidationException
//1: 若此时未更新 非必填字段,则数据库会把非必填字段更新为null
contextState.Entry<CustomerInfo>(customerState).State = System.Data.EntityState.Modified;
contextState.SaveChanges();
//EF context 对象
DbContext contextState = new MyFirstEFEntities(); //update 2
CustomerInfo customerState = new CustomerInfo();
customerState.id = ;
customerState.customerName = "dfdfdfdf"; //2: 针对某个属性,进行状态跟踪设置
//** 2.1: 如果使用 Entry 附加 实体对象到数据容器中,则需要手动 设置 实体包装类的对象 的 状态为 Unchanged**
//** 2.1: entry.State = System.Data.EntityState.Unchanged;
DbEntityEntry<CustomerInfo> entry = contextState.Entry<CustomerInfo>(customerState);
entry.State = System.Data.EntityState.Unchanged;
entry.Property("customerName").IsModified = true;
contextState.SaveChanges();
//EF context 对象
DbContext contextState = new MyFirstEFEntities(); //update 3
CustomerInfo customerState = new CustomerInfo();
customerState.id = ;
customerState.customerName = "aaaaa"; //** 2.2: 如果使用 Attach 就不需要这句
//** 2.2: entry.State = System.Data.EntityState.Unchanged;
contextState.Set<CustomerInfo>().Attach(customerState);///直接针对属性进行状态设置,但是当前对象并没有被上下文跟踪
contextState.Entry<CustomerInfo>(customerState).Property("customerName").IsModified = true;
contextState.SaveChanges();
EF其他操作(多表增加操作/导航属性):
#region 多表增加操作
DbContext dbContext = new MyFirstEFEntities(); CustomerInfo customerInfo = new CustomerInfo()
{
customerName = "duobiaocaozuo",
customerDate = DateTime.Now
};
dbContext.Set<CustomerInfo>().Add(customerInfo); OrderInfo orderInfo1 = new OrderInfo()
{
orderName = "bike1",
customerId = customerInfo.id
};
dbContext.Set<OrderInfo>().Add(orderInfo1); OrderInfo orderInfo2 = new OrderInfo()
{
orderName = "bike2",
customerId = customerInfo.id
};
dbContext.Set<OrderInfo>().Add(orderInfo2); dbContext.SaveChanges();
#endregion
#region 导航属性
DbContext dbContext = new MyFirstEFEntities(); CustomerInfo customerInfo = new CustomerInfo()
{
customerName = "daohangshuxing",
customerDate = DateTime.Now
}; customerInfo.OrderInfoes.Add(new OrderInfo()
{
orderName = "car1",
}); customerInfo.OrderInfoes.Add(new OrderInfo()
{
orderName = "car2"
}); dbContext.Set<CustomerInfo>().Add(customerInfo); dbContext.SaveChanges(); #endregion
 using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _20160403_MyFirstEFDemo
{
class Program
{
static void Main(string[] args)
{ #region 方法
////EF context 对象
//MyFirstEFEntities context = new MyFirstEFEntities();
////add
//CustomerInfo customer = new CustomerInfo();
//customer.customerName = "Test1";
//customer.customerDate = DateTime.Now;
//context.CustomerInfoes.Add(customer);
//context.SaveChanges(); ////update
////1:先查询要修改的原数据
//CustomerInfo customer = context.CustomerInfoes.Find(1);
////2:设置修改后的值
//customer.customerDate = DateTime.Now;
////3:更新到数据库
//context.SaveChanges(); ////Read
//CustomerInfo customer = context.CustomerInfoes.Find(1);
//if (customer != null)
//{
// string strCustomerInfo = string.Format("name:{0},date:{1}", customer.customerName, customer.customerDate);
// Console.WriteLine(strCustomerInfo);
//} ////delete
//CustomerInfo customer = new CustomerInfo();
//customer.id = 1;
//context.CustomerInfoes.Attach(customer);
//context.CustomerInfoes.Remove(customer);
//context.SaveChanges();
#endregion #region 状态
//EF context 对象
//DbContext contextState = new MyFirstEFEntities(); ////add 1
//CustomerInfo customerState = new CustomerInfo();
//customerState.customerName = "testState1";
//customerState.customerDate = DateTime.Now;
//contextState.Set<CustomerInfo>().Add(customerState);
//contextState.SaveChanges(); ////add 2
//CustomerInfo customerState = new CustomerInfo() {
// customerName="stateTest111",
// customerDate=DateTime.Now
//};
//contextState.Entry<CustomerInfo>(customerState).State = System.Data.EntityState.Added;
//contextState.SaveChanges(); ////update 1
//CustomerInfo customerState = new CustomerInfo();
//customerState.id = 1;
//customerState.customerDate = DateTime.Now;
//customerState.customerName = "bbb"; ////1: 标记当前对象,必须把必填字段都填写,否则会报错:System.Data.Entity.Validation.DbEntityValidationException
////1: 若此时未更新 非必填字段,则数据库会把非必填字段更新为null
//contextState.Entry<CustomerInfo>(customerState).State = System.Data.EntityState.Modified;
//contextState.SaveChanges(); ////update 2
//CustomerInfo customerState = new CustomerInfo();
//customerState.id = 1;
//customerState.customerName = "dfdfdfdf"; ////2: 针对某个属性,进行状态跟踪设置
////** 2.1: 如果使用 Entry 附加 实体对象到数据容器中,则需要手动 设置 实体包装类的对象 的 状态为 Unchanged**
////** 2.1: entry.State = System.Data.EntityState.Unchanged;
//DbEntityEntry<CustomerInfo> entry = contextState.Entry<CustomerInfo>(customerState);
//entry.State = System.Data.EntityState.Unchanged;
//entry.Property("customerName").IsModified = true;
//contextState.SaveChanges(); ////update 3
//CustomerInfo customerState = new CustomerInfo();
//customerState.id = 1;
//customerState.customerName = "aaaaa"; ////** 2.2: 如果使用 Attach 就不需要这句
////** 2.2: entry.State = System.Data.EntityState.Unchanged;
//contextState.Set<CustomerInfo>().Attach(customerState);///直接针对属性进行状态设置,但是当前对象并没有被上下文跟踪
//contextState.Entry<CustomerInfo>(customerState).Property("customerName").IsModified = true;
//contextState.SaveChanges(); ////delete
//CustomerInfo customerState = new CustomerInfo()
//{
// id = 2
//};
//contextState.Entry<CustomerInfo>(customerState).State = System.Data.EntityState.Deleted;
//contextState.SaveChanges(); #endregion #region 多表增加操作
//DbContext dbContext = new MyFirstEFEntities(); //CustomerInfo customerInfo = new CustomerInfo()
//{
// customerName = "duobiaocaozuo",
// customerDate = DateTime.Now
//};
//dbContext.Set<CustomerInfo>().Add(customerInfo); //OrderInfo orderInfo1 = new OrderInfo()
//{
// orderName = "bike1",
// customerId = customerInfo.id
//};
//dbContext.Set<OrderInfo>().Add(orderInfo1); //OrderInfo orderInfo2 = new OrderInfo()
//{
// orderName = "bike2",
// customerId = customerInfo.id
//};
//dbContext.Set<OrderInfo>().Add(orderInfo2); //dbContext.SaveChanges();
#endregion #region 导航属性
//DbContext dbContext = new MyFirstEFEntities(); //CustomerInfo customerInfo = new CustomerInfo()
//{
// customerName = "daohangshuxing",
// customerDate = DateTime.Now
//}; //customerInfo.OrderInfoes.Add(new OrderInfo()
//{
// orderName = "car1",
//}); //customerInfo.OrderInfoes.Add(new OrderInfo()
//{
// orderName = "car2"
//}); //dbContext.Set<CustomerInfo>().Add(customerInfo); //dbContext.SaveChanges(); #endregion Console.WriteLine("OK");
Console.ReadKey();
}
}
}

EF(方法/状态/多表操作/导航属性)整体测试代码

参考文章:

ASP.NET EF(LINQ/Lambda查询):http://www.cnblogs.com/Dr-Hao/p/5356928.html

ASP.NET EF 使用LinqPad 快速学习Linq:http://www.cnblogs.com/Dr-Hao/p/5357112.html

Ps:ViewBag,ViewData,TempData区别?

ViewBag 和 ViewData 数据"共享",作用域为 当前 Action。

TempData 作用域跨 Action。

ASP.NET MVC EF直接更新数据(不需查询)的更多相关文章

  1. EF直接更新数据(不需查询)

    //0.0创建修改的 实体对象 Models.BlogArticle model = new BlogArticle(); model.AId = ; model.ATitle = "新的数 ...

  2. CakePHP采用model的save方法更新数据所需查询

    采用model的save方法更新数据所需查询 1. 验证时候要确认是update 或者 create,以便使用对应规则 public $validate = array( 'field_name' = ...

  3. [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序更新相关数据

    这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第八篇:为ASP.NET MVC应用程序 ...

  4. ASP.NET MVC + EF 利用存储过程读取大数据,1亿数据测试很OK

    看到本文的标题,相信你会忍不住进来看看! 没错,本文要讲的就是这个重量级的东西,这个不仅仅支持单表查询,更能支持连接查询, 加入一个表10W数据,另一个表也是10万数据,当你用linq建立一个连接查询 ...

  5. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除)

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除) ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   ...

  6. ASP.NET MVC + EF 利用存储过程读取大数据

    ASP.NET MVC + EF 利用存储过程读取大数据,1亿数据测试很OK 看到本文的标题,相信你会忍不住进来看看! 没错,本文要讲的就是这个重量级的东西,这个不仅仅支持单表查询,更能支持连接查询, ...

  7. ASP.NET MVC应用程序更新相关数据

    为ASP.NET MVC应用程序更新相关数据 这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译, ...

  8. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(23)-设置角色遗留问题和为权限设置角色以及EasyUI Tabs的使用

    ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架搭建    (2):数据库访问层的设计Demo    (3):面向接口编程   (4 ):业务逻辑层的封装    ...

  9. ASP.NET MVC+EF框架+EasyUI实现权限管理系列

    http://www.cnblogs.com/hanyinglong/archive/2013/03/22/2976478.html ASP.NET MVC+EF框架+EasyUI实现权限管理系列之开 ...

随机推荐

  1. 【beta】Scrum站立会议第4次....11.6

    小组名称:nice! 组长:李权 成员:于淼  刘芳芳韩媛媛 宫丽君 项目内容:约跑app(约吧) 时间:  12:00——12:30 地点:传媒西楼220室 本次对beta阶段的需求进行更新如下: ...

  2. C# 7.0 本地方法

    VS 2017 的 C# 7.0 中引入了本地方法,本地方法是一种语法糖,允许我们在方法内定义本地方法.更加类似于函数式语言,但是,本质上还是基于面向对象实现的. 1. 本地方法 先看一个示例: 1 ...

  3. 【ABP】Abp的AspNetZero5.0版本无法使用ctrl+f5调式

    原文:http://www.cnblogs.com/94pm/p/7942483.html AspNetZero是基于Abp框架开发的商业程序,最近从Abp交流群中得知5.0版本开始加入了防盗版的功能 ...

  4. Strus默认跳转方式是请求转发 地址栏不变 与javaweb的内部转发一样

    Strus默认跳转方式是请求转发 地址栏不变 与javaweb的内部转发一样

  5. Golang的第一个程序-Hello, World !

    安装Golang: 1. 下载安装包 https://golang.google.cn/dl/ 我这里使用压缩包,下载后解压到D盘(自定义). 2. 添加环境变量:把解压后的bin目录添加到环境变量中 ...

  6. 【刷题】LOJ 6038 「雅礼集训 2017 Day5」远行

    题目描述 Miranda 生活的城市有 \(N\) 个小镇,一开始小镇间没有任何道路连接.随着经济发现,小镇之间陆续建起了一些双向的道路但是由于经济不太发达,在建设过程中,会保证对于任意两个小镇,最多 ...

  7. 测试开发面试的Linux面试题总结之二:常用命令

    (1)Linux的文件系统目录配置要遵循FHS规范,规范定义的两级目录规范如下:        /home  每个账号在该目录下都有一个文件夹,进行数据的管理        /usr 有点像windo ...

  8. 小Z的袜子 题解报告【莫队】

    Description 作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿.终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命-- 具体来说,小Z把这N只 ...

  9. 电子商务(电销)平台中用户模块(User)数据库设计明细

    以下是自己在电子商务系统设计中的订单模块的数据库设计经验总结,而今发表出来一起分享,如有不当,欢迎跟帖讨论~ 用户基础表(user_base)|-- 自动编号 (user_id)|-- 用户名 (us ...

  10. day4-python基础