当前位置: 首页 > 编程日记 > 正文

Entity Framework学习三:查询、插入、更新和删除操作

1.LINQ过滤数据 

var query = from person in context.Peoplewhere person.FirstName.StartsWith("a")select person;
var methodQuery = context.People.Where(p => p.FirstName.StartsWith("a"));

两种不同的写法,效果一样。

  • 多条件组合查找
var query = from person in context.Peoplewhere person.FirstName.StartsWith("a") &&person.LastName.EndsWith("b")select person;
var methodQuery = context.People.Where(p => p.FirstName.StartsWith("a") && p.LastName.EndsWith("b"));
  • 对查找结果排序升序:
            var query = from person in context.Peoplewhere person.FirstName.StartsWith("a") &&person.LastName.EndsWith("b")orderby person.FirstName,person.LastNameselect person;var methodQuery = context.People.Where(p => p.FirstName.StartsWith("a") && p.LastName.EndsWith("b")).OrderBy(p => p.FirstName).ThenBy(p => p.LastName);
  • 对查找结果排序降序:
            var query = from person in context.Peoplewhere person.FirstName.StartsWith("a") &&person.LastName.EndsWith("b")orderby person.FirstName,person.LastNamedescendingselect person;var methodQuery = context.People.Where(p => p.FirstName.StartsWith("a") && p.LastName.EndsWith("b")).OrderByDescending(p => p.FirstName).ThenByDescending(p => p.LastName);
  • 延迟加载和贪婪加载(Lazy Loading和eager loading)

如果不确定是否要加载关联数据时就使用延迟加载,否则就使用贪婪加载。当然这个不是固定的看具体什么场景下使用。默认情况下延迟加载是生效的,可以在创建DbContex后配置选项

context.Configuration.LazyLoadingEnabled = false;

2.插入数据

多种方法,不多说看代码:

  • 方法一
var person = new Person
{
BirthDate = new DateTime(1980, 1, 2),
FirstName = "John",
HeightInFeet = 6.1M,
IsActive = true,
LastName = "Doe",
MiddleName = "M"
};
person.Phones.Add(new Phone { PhoneNumber = "1-222-333-4444" });
person.Phones.Add(new Phone { PhoneNumber = "1-333-4444-5555" });
using (var context = new Context())
{
context.People.Add(person);
context.SaveChanges();
}

方法二:改变Entity的状态

using (var context = new Context())
{
context.Entry(person2).State = EntityState.Added;
context.SaveChanges();
}

EntityState:Added、Deleted、Detached(DbContex不追踪Entity状态)、Modified、Unchanged

3.更新数据

多种方法:

方法一:

using (var context = new Context())
{
var person = context.People.Find(1);
person.FirstName = "New Name";
context.SaveChanges();
}

方法二(建议使用)注意标记部分:

var person2 = new Person
{
PersonId = 1,
BirthDate = new DateTime(1980, 1, 2),
FirstName = "Jonathan",
HeightInFeet = 6.1m,
IsActive = true,
LastName = "Smith",
MiddleName = "M"
};
person2.Phones.Add(new Phone
{
PhoneNumber = "updated 1",
PhoneId = 1,
PersonId = 1
});
person2.Phones.Add(new Phone
{
PhoneNumber = "updated 2",
PhoneId = 2,
PersonId = 1
});
using (var context = new Context())
{
context.Entry(person2).State = EntityState.Modified;
context.SaveChanges();
}

你会发现执行上面代码只有Person数据更新了,Phone数据没有更新,这是因为Insert和Update机制不一样,Update时设置了Entity的EntityState,但是并没有传播到子数据的状态,需要都上面程序做些修改

using (var context = new Context())
{
context.Entry(person2).State = EntityState.Modified;
foreach (var phone in person2.Phones)
{
context.Entry(phone).State = EntityState.Modified;
}
context.SaveChanges();
}

在开发Web程序时可以使用AsNoTracking来提高查询性能

using (var context = new Context())
{
var query = context.People.Include(p =>
p.Phones).AsNoTracking();
foreach (var person in query)
{
foreach (var phone in person.Phones)
{
}
}
}
  • 使用Attach 会改变状态为Unchanged,并开始追踪Entity的状态
var person3 = new Person
{
PersonId = 1,
BirthDate = new DateTime(1980, 1, 2),
FirstName = "Jonathan",
HeightInFeet = 6.1m,
IsActive = true,
LastName = "Smith",
MiddleName = "M"
};
using (var context = new Context())
{
context.People.Attach(person3);
person3.LastName = "Updated";
context.SaveChanges();
}

上面代码执行将仅仅只会更新LastName列。也可以用以下代码替代Attach方法

context.Entry(person3).State = EntityState.Unchanged

4.删除数据

  • 方法一:先查询出数据,再删除(注意删除子数据可以使用设置数据库级联删除更方便)
using (var context = new Context())
{
var toDelete = context.People.Find(personId);
toDelete.Phones.ToList().ForEach(phone =>context.Phones.Remove(phone));
context.People.Remove(toDelete);
context.SaveChanges();
}
  • 方法二:使用改变状态
var toDeleteByState = new Person { PersonId = personId };
toDeleteByState.Phones.Add(new Phone
{
PhoneId = phoneId1,
PersonId = personId
});
toDeleteByState.Phones.Add(new Phone
{
PhoneId = phoneId2,
PersonId = personId
});
using (var context = new Context())
{
   context.People.Attach(toDeleteByState);
   foreach (var phone in toDeleteByState.Phones.ToList()){context.Entry(phone).State = EntityState.Deleted;}context.Entry(toDeleteByState).State = EntityState.Deleted;context.SaveChanges();
}

5.查询本地数据

当需要查询的数据已经在内存中,而未提交到数据库时对内存数据进行查询

var localQuery = context.People.Local.Where(p =>
p.LastName.Contains("o")).ToList();

转载于:https://www.cnblogs.com/zjmsky/p/4823847.html

相关文章:

c/s开发基础自学纪录为主

1.常用属性 (1)Name属性:用来获取或设置窗体的名称。 (2)WindowState属性:用来获取或设置窗体的窗口状态。 (3)StartPosition属性:用来获取或设置运行时窗体的…

不错的威盾PHP加密专家解密算法

<?php /*********************************** *威盾PHP加密专家解密算法 http://www.my400800.cn ***********************************/ $filename"phpfilename.php";//要解密的文件 $lines file($filename);//0,1,2行 //第一次base64解密 $content"&quo…

java网络编程udp_java网络编程 UDP网络编程问题

为什么我的代码运行后&#xff0c;黑窗口&#xff0c;不显示一端发来的数据&#xff0c;而是黑窗口打印很多空格&#xff1f;请帮一下&#xff0c;初学者&#xff01;谢谢&#xff0c;下面是二个具有发送和接受功能的代码&#xff1f;发送端————importjava.net.*;imp...为什…

权限组件(10):三级菜单的展示和增删改查

效果图&#xff1a; 三级菜单的实现和一级、二级菜单差不多。需要注意的是增加三级菜单时&#xff0c;三级菜单是用户提交后在后台通过二级菜单的id添加的。 一、路由分发 rbac/urls.py ... from django.urls import re_pathfrom rbac.views import menu ...urlpatterns [...…

ROS知识(4)----初级教程之常见问题汇总

一、开机启动ROS的工作空间的路径设置失败 现象&#xff1a;在教程&#xff1a;http://wiki.ros.org/cn/ROS/Tutorials/CreatingPackage中的第5.1小节&#xff0c;运行以下命令失败&#xff1a; $ rospack depends1 beginner_tutorials 提示错误&#xff1a;[rospack] Error: …

sql server 海量数据速度提升:SQL优化-索引(11) 【转】

12、高效的TOP 事实上&#xff0c;在查询和提取超大容量的数据集时&#xff0c;影响数据库响应时间的最大因素不是数据查找&#xff0c;而是物理的I/0操作。如&#xff1a; select top 10 * from ( select top 10000 gid,fariqi,title from tgongwen where neibuyonghu办公室or…

java重定向带参数_急 求助重新封装重定向带参数问题

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼这是我写的代码 不知道行不行 求助package base.web.resolver.result;import java.util.HashMap;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.logging.log4j.…

Java程序员从笨鸟到菜鸟之(五)java开发常用类(包装,数字处理集合等)(下)...

本文来自&#xff1a;曹胜欢博客专栏。转载请注明出处&#xff1a;http://blog.csdn.net/csh624366188 写在前面&#xff1a;由于前天项目老师建设局的项目快到验收阶段&#xff0c;所以&#xff0c;前天晚上通宵&#xff0c;昨天睡了大半天&#xff0c;下午我们宿舍聚会&#…

对数组中的数字 1 和 2 进行排序,使得数字 1、2 分别位于前、后部分

问题描述&#xff1a;假设某个数组中只有数字 1 和 2&#xff0c;进行排序&#xff0c;使得数字 1 位于数组前部分&#xff0c;数字 2 位于后部分。 这道算法题其实不是很难&#xff0c;使用各种排序算法应该都能解出&#xff0c;但是若要考虑性能问题&#xff0c;那就得选择一…

@class和#import

class 作用&#xff1a; 可以简单的引用一个类 简单使用&#xff1a; class Dog; 仅仅是告诉编译器&#xff0c;Dog是一个类&#xff1b;并不会包含Dog这个类的所有内容 具体使用&#xff1a; 在.h文件中使用class引用一个类 在.m文件中使用#import包含这个类的.h文件 作用上的…

java登陆界面连接数据库_java 登陆界面怎么写,连接数据库后

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼界面是package 界面类;import javax.jws.soap.SOAPBinding.Use;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing…

C# 汉字编码GB2312转换

功能界面 源码&#xff1a; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;namespace wordsConvert {public partial class Fo…

python批量爬取文档

最近项目需要将批量链接中的pdf文档爬下来处理&#xff0c;根据以下步骤完成了任务&#xff1a; 将批量下载链接copy到text中&#xff0c;每行1个链接&#xff1b;再读txt文档构造url_list列表&#xff0c;利用readlines返回以行为单位的列表&#xff1b;利用str的rstrip方法&a…

[Android]webview直接加载网页允许JS,进度条,当前应用内跳转

webview&#xff0c;用于在应用里面直接加载网页本代码参考了&#xff1a;官方的webview实例介绍&#xff1a;https://developer.android.com/guide/tutorials/views/hello-webview.html 加上进度条&#xff1a; http://blog.csdn.net/stoneson/article/details/6068089 整个源…

ubuntu 14.04 安装java_Ubuntu 14.04中安装Java

第三&#xff1a;在Ubuntu 和 Linux Mint上安装Java看了各种类型"java";的不同之后&#xff0c;让我们看如何安装他们。1)在Ubuntu和Linux Mint上安装JRE打开终端&#xff0c;使用下面的命令安装JRE&#xff1a;sudo apt-get install default-jre2)在Ubuntu和Linux M…

C# 生成系统唯一号

生成唯一号&#xff1a;思路&#xff0c;根据yymmddhhmmss自增长号唯一服务器号( SystemNo)生成唯一码&#xff0c;总长度19&#xff0c;例如&#xff1a;1509281204550000101. public class UniqueNumber{private static long num 0;//流水号private static object lockObj …

EBS上用过的一些接口表整理信息

AP接口表&#xff1a;AP_INVOICES_INTERFACEAP_INVOICE_LINES_INTERFACE涉及的请求&#xff1a;应付款管理系统开放接口导入涉及案例&#xff1a; 运费导AP、费用导APPO接口表&#xff1a;申请&#xff1a;PO_REQUISITIONS_INTERFACE_ALL涉及请求&#xff1a;导入申请采购&…

linux源码编译安装nginx

1.从nginx的官方网站下载nginx的安装源码包&#xff0c;要下载.gz格式的包才是linux安装包 网址http://nginx.org/download/ wget http://nginx.org/download/nginx-1.5.9.tar.gz 2.解压 tar -zxvf nginx-1.5.9.tar.gz yum -y install pcre-devel gcc gcc-c autoconf automak…

usr share里没有mysql_无法在ubuntu 12.04上安装mysql,找不到消息文件’/usr/share/mysql/errmsg.sys’...

尝试使用apt-get安装mysql但它失败了# apt-get install MysqL-serverReading package lists... DoneBuilding dependency treeReading state information... DoneThe following extra packages will be installed:MysqL-server-5.5Suggested packages:tinycaThe following NEW …

android:更改PagerTabStrip背景颜色,标题字体样式、颜色和图标,以及指示条的颜色...

1.更改PagerTabStrip背景颜色我们直接在布局中设置background属性可以&#xff1a;<android.support.v4.view.ViewPagerandroid:id"id/pager"android:layout_width"fill_parent"android:layout_height"fill_parent" ><android.support.…

敏捷开发日常跟进系列之二:燃尽图(中)

这是敏捷开发日常跟进系列的第二篇&#xff08;栏目目录&#xff09;。 迭代及燃尽图的目标 燃尽图的目标是完成迭代的目标&#xff0c;迭代的目标是什么呢&#xff1f; 1. 按产品经理的要求&#xff0c;交付计划会中计划的用户故事 2. 尽量完成1 之后还会看到&#xff0c;这个…

[python][jupyter notebook]之菜鸟安装[pyecharts]中Geo或Map显示问题

作为菜鸟&#xff0c;在学习使用pyecharts模块进入jupyter notebook的时候&#xff0c;又遇到了问题——那就是&#xff0c;可以使用一下代码&#xff0c;导入Geo和Map模块&#xff0c;但是弄了之后看不见地图。 from pyecharts import Geo from pyecharts import Map 所以&…

c语言多线程mysql_多线程读写mysql数据库

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼unsigned int __stdcall scan(PVOID pM){char ip[20];strcpy(ip, (char*)pM);MYSQL mysql;MYSQL_RES* result;//初始化mysql句柄mysql_init(&mysql);//连接mysql数据库if(!mysql_real_connect(&mysql,"localhost"…

[C#,Java,PHP] - IMAP文件夹名称编码和解码方法

[C#] 来源&#xff1a;http://www.oschina.net/code/snippet_110991_2237 // 编码private string IMAPEncode(string folder){string rtn "", base64;int index 0; Regex regAsis new Regex("\G(?:[\x20-\x25\x27-\x7e])"); Regex reg26 new Rege…

fzu 2150 Fire Game 【身手BFS】

称号&#xff1a;fzu 2150 Fire Game &#xff1a;给出一个m*n的图&#xff0c;‘#’表示草坪&#xff0c;‘ . ’表示空地&#xff0c;然后能够选择在随意的两个草坪格子点火。火每 1 s会向周围四个格子扩散&#xff0c;问选择那两个点使得燃烧全部的草坪花费时间最小&#xf…

K-Means聚类算法原理

来自&#xff1a;https://www.cnblogs.com/pinard/p/6164214.html K-Means算法是无监督聚类算法&#xff0c;它有很多变体。包括初始化优化K-Means&#xff0c;距离计算优化elkan K-Means算法和大样本优化Mini Batch K-Means算法。 1. K-Means原理 K-Means算法思想&#xff1a;…

safari java插件故障_safari flash插件故障怎么办 mac safari flash插件故障解决方法

近几日&#xff0c;许多网友都在关注safari flash插件故障怎么办 mac safari flash插件故障解决方法这个话题&#xff0c;那么safari flash插件故障怎么办 mac safari flash插件故障解决方法具体情况是怎么样的呢&#xff1f;safari flash插件故障怎么办 mac safari flash插件故…

Traveller项目介绍

Traveller&#xff0c;翻译为旅行家&#xff0c;是我用来实践最佳web技术的项目&#xff0c;主题是一个给旅行爱好者提供旅行信息的网站。 目标是组合现最流行的web技术&#xff0c;实现符合中国用户使用习惯的网站。 相关网址 Git&#xff1a;https://github.com/mingziday/Tr…

窗口之间传递消息的一个方法

发送窗口的代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Wi…

docker制作镜像篇(基于容器)

docker制作镜像可以有两种方式&#xff1a;一、基于容器&#xff08;使用busybox制作http镜像&#xff09;1.首先运行一个容器2.在容器当中配置自己的http&#xff0c;添加web目录&#xff0c;增加主页文件等。3.查看原busybox运行容器时的默认启动程序&#xff08;原运行命令为…