ASP.NET MVC EF直接更新数据(不需查询)
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();
#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直接更新数据(不需查询)的更多相关文章
- EF直接更新数据(不需查询)
//0.0创建修改的 实体对象 Models.BlogArticle model = new BlogArticle(); model.AId = ; model.ATitle = "新的数 ...
- CakePHP采用model的save方法更新数据所需查询
采用model的save方法更新数据所需查询 1. 验证时候要确认是update 或者 create,以便使用对应规则 public $validate = array( 'field_name' = ...
- [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序更新相关数据
这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第八篇:为ASP.NET MVC应用程序 ...
- ASP.NET MVC + EF 利用存储过程读取大数据,1亿数据测试很OK
看到本文的标题,相信你会忍不住进来看看! 没错,本文要讲的就是这个重量级的东西,这个不仅仅支持单表查询,更能支持连接查询, 加入一个表10W数据,另一个表也是10万数据,当你用linq建立一个连接查询 ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除)
原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除) ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) ...
- ASP.NET MVC + EF 利用存储过程读取大数据
ASP.NET MVC + EF 利用存储过程读取大数据,1亿数据测试很OK 看到本文的标题,相信你会忍不住进来看看! 没错,本文要讲的就是这个重量级的东西,这个不仅仅支持单表查询,更能支持连接查询, ...
- ASP.NET MVC应用程序更新相关数据
为ASP.NET MVC应用程序更新相关数据 这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译, ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(23)-设置角色遗留问题和为权限设置角色以及EasyUI Tabs的使用
ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) (1):框架搭建 (2):数据库访问层的设计Demo (3):面向接口编程 (4 ):业务逻辑层的封装 ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列
http://www.cnblogs.com/hanyinglong/archive/2013/03/22/2976478.html ASP.NET MVC+EF框架+EasyUI实现权限管理系列之开 ...
随机推荐
- PAT 甲级 1041 Be Unique
https://pintia.cn/problem-sets/994805342720868352/problems/994805444361437184 Being unique is so imp ...
- linux svn启动和关闭
linux svn启动和关闭 博客分类: linux系统 svnlinux 1,启动SVN sudo svnserve -d -r /home/data/svn/ 其中 -d 表示守护进程, -r ...
- larave5.6 引入自定义函数库时,报错不能重复定义
方法一:使用function_exists判断 方法二:使用命名空间 namespace test; function test(){ echo 'test/test'; } namespace te ...
- 我的系统资源呢?php-fpm你知道吗?
1:别的先不管咱们top一下.看看咱们的cpu ram swap的使用情况 由上图分析,可以看出共有602个进程,其中有601个进程休眠了.这好像有点不对劲,内核进程也就80个左右,加上memcach ...
- HDU4803_Poor Warehouse Keeper
题目很有意思,我想说其实我在比赛的时候就看过了一下这个题目,今天才这么快搞出来吧. 其实总共按上键的次数不会超过10个,我们可以每次假设相隔按两次上键之间按了xi次下键,由于上键的次数是确定的,所以最 ...
- AtCoder Regular Contest 083 D: Restoring Road Network
题意 有一张无向带权连通图(点数<=300),给出任意两点i,j之间的最短路长度dis[i][j].问是否存在一张这样的无向图.如果不存在输出-1.如果存在输出所有这样的无向图中边权和最小的一张 ...
- BZOJ4921 互质序列
即求删掉一个子序列的gcd之和.注意到前后缀gcd的变化次数都是log级的,于是暴力枚举前缀gcd和后缀gcd即可. #include<iostream> #include<cstd ...
- 洛谷 P2146 [NOI2015]软件包管理器
真没有想到,这竟然会是一道NOI的原题,听RQY说,这套题是北大出的,北大脑抽认为树剖很难... 只恨没有早学几年OI,只A这一道题也可以出去吹自己一A了NOI原题啊 好了,梦该醒了,我们来看题 以后 ...
- gpart 分区工具
gpart 分区工具 https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/disk-organization.html Table 3 ...
- Oracle 多表关联并且批量修改
描述:A表有 id,or_id 字段,B表有 id,code 字段 A表有 or_id 与B表的 id 关联,现要将A.or_id 替换成 B.code 数据 UPDATE AS ...