Linq To Entities 及其相关(进阶)
上篇我们讲解了Linq To Entities的一些基本操作,这篇我们主要是讲解一些比较高级的东西:存储过程查询,SQL语句查询以及表达式树。
存储过程
首先来讲解存储过程查询。
//Query a stored procedure.(查询存储过程)
var tenExpensiveP = from p in nWEntities.Ten_Most_Expensive_Products()
select p;
foreach (var product in tenExpensiveP)
{
Console.WriteLine("Stored Procedure scenario: ProductName:{0},Price:{1}", product.TenMostExpensiveProducts, product.UnitPrice);
}
Console.WriteLine("=============================================");
在存储过程这块,我们首先需要做的是导入数据库中的存储过程对象。步骤如下:
1.双击Northwind.edmx,在左边的空白处右击,选择“从数据库更新模型”。
2.在弹出的“更新向导”窗口中,选中自己需要添加的存储过程:Ten_Most_Expensive_Products,之后点击完成按钮。
3.在左边的空白处右击,选择”添加“->”函数导入”,在弹出的”添加函数导入“对话框中,”函数导入名称“填写Ten_Most_Expensive_Products,然后在下面的”存储过程名称”中,下拉选择“Ten_Most_Expensive_Products”。之后点击“获取列信息”,可以看到返回的列已经显示在了下面的列表中。然后单击“创建新的复杂类型”按钮,则“复杂”单选框被激活,并且其后的文本框中自动会填充“Ten_Most_Expensive_Products”文本。做好这一切之后,点击“确定”按钮即可。
4.步骤3操作完毕后,Ten_Most_Expensive_Products实体类就被添加到了项目中,我们可以像操作其他实体类一样操作这个存储过程。
预编译查询
之后我们需要提到的是预编译查询。预编译查询主要是用于多个相似的查询存在的情况下,比如我在同一张表中第一次查询张三,第二次查询李四,那么我不必分两次去数据库拿数据,只要通过预编译查询,一次把所有需要的数据提取出来即可。
//Compiled Query
//如果相同的查询操作在许多地方被使用,那么可以提前编译好需要执行的查询操作,然后在多个地方使用,可以提高Performance
Func<NorthWindEntities, string, IQueryable<Product>> func =
CompiledQuery.Compile((NorthWindEntities NW, string category) =>from p in NW.Products where p.Category.CategoryName == category select p);
var product1 = func(nWEntities, "Beverages");
Console.WriteLine("Compiled query scenario: Total Products in category Beverages:{0}", product1.Count());
var product2 = func(nWEntities, "Seafood");
Console.WriteLine("Compiled query scenario: Total Products in category Seafood: {0}",product2.Count());
Console.WriteLine("=============================================");
其实上面你的代码只查询了数据库一次,但是可以在两个地方使用。
直接执行SQL语句
这里我们需要说到的是怎么在Linq to entities中执行sql语句。有时候当sql过于复杂的时候,我们完全可以利用原生的sql语句来查询。
//Direct SQL(直接是用SQL语句)
var products = nWEntities.ExecuteStoreQuery<Product>("SELECT * FROM Products WHERE Discontinued = 0 ORDER BY ProductName;");
Console.WriteLine("Direct SQL: Total discontinued products :{0}", products.Count()); int rowCount = nWEntities.ExecuteStoreCommand(" update products set UnitPrice=UnitPrice+1 where productID=35 ");
if (rowCount < 1) Console.WriteLine("Direct SQL: No product is updated.");
if (rowCount >= 1) Console.WriteLine("Direct SQL: Product is updated.");
Console.WriteLine("=============================================");
这里有两个方法:ExecuteStoreQuery用于提供查询操作;ExecuteStoreCommand用于提供执行操作。
表达式树
接下来是表达式树的说明,由于这个涉及的范围比较广,暂时先略过讲解,待之后慢慢研究:
//Expression Tree(表达式树)
ParameterExpression param = Expression.Parameter(typeof(Product),"p");
Expression left = Expression.Property(param,typeof(Product).GetProperty("UnitPrice"));
Expression right = Expression.Constant((decimal)100, typeof(Nullable<decimal>));
Expression filter = Expression.GreaterThanOrEqual(left,right);
Expression pred = Expression.Lambda(filter,param);
Console.WriteLine(pred.ToString()); //输出 p=>(p.UnitPrice>=100) IQueryable productList = nWEntities.Products;
Expression expr = Expression.Call(typeof(Queryable)
, "Where"
, new Type[] { typeof(Product)}
, Expression.Constant(productList)
, pred);
expr = Expression.Call(typeof(Queryable)
, "OrderBy"
, new Type[] { typeof(Product), typeof(string) }
, expr
, Expression.Lambda(Expression.Property(param, "ProductName"), param));
Console.WriteLine(expr.ToString()); IQueryable<Product> query = nWEntities.Products.AsQueryable().Provider.CreateQuery<Product>(expr);
foreach (var p in query)
{
Console.WriteLine("Expression Tree scenario: Product name: {0}",p.ProductName);
}
Console.WriteLine("=============================================");
带参动态查询
//Dynamic Query with parameters(带参的动态查询)
string querystring = "select value product from NorthwindEntities.Products as Product where Product.ProductID = @id";
ObjectQuery<Product> productQuery = new ObjectQuery<Product>(querystring, nWEntities);
productQuery.Parameters.Add(new ObjectParameter("id", 1));
foreach (var p in productQuery)
{
Console.WriteLine("Dynamic query with parameters: ProductName {0}",p.ProductName);
}
这里我们可以利用ObjectQuery的Parameters属性动态添加参数。
Linq To Entities 及其相关(进阶)的更多相关文章
- Linq To Entities 及其相关
说到Linq,很多人都非常熟悉,我们可以很方便的用它来操纵对象的集合.今天要说的是Linq To Entities及其相关的操作.下面一步一步的来进行.这里我着重强调的是语法上面的一些注意点.所以怎么 ...
- LINQ to Entities 查询语法
转自: http://www.cnblogs.com/asingna/archive/2013/01/28/2879595.html 实体框架(Entity Framework )是 ADO.NET ...
- LINQ(LINQ to Entities)
LINQ to Entities 是 LINQ 中最吸引人的部分.它让你可以使用标准的 C# 对象与数据库的结构和数据打交道.使用 LINQ to Entities 时,LINQ 查询在后台转换为 S ...
- C#_LINQ(LINQ to Entities)
LINQ to Entities 是 LINQ 中最吸引人的部分.它让你可以使用标准的 C# 对象与数据库的结构和数据打交道.使用 LINQ to Entities 时,LINQ 查询在后台转换为 S ...
- LINQ to Entities 查询中的标准查询运算符
投影和筛选方法 投影指的是转换的结果集到所需的窗体中的元素. 例如,可以从结果集中的每个对象投影所需的属性子集,可以投影一个属性并对其执行数学计算,也可以从结果集投影整个对象. 投影方法有 Selec ...
- LINQ to Entities 不支持 LINQ 表达式节点类型“ArrayIndex”
我就不屁话,能一张图就解决的就不说话了 2015-03-28 14:53:24,440 [10] ERROR log - System.NotSupportedException: LINQ to E ...
- 【转】Entity Framework技术系列之7:LINQ to Entities
前言 LINQ(Language Integrated Query,语言集成查询)是一组用于C#和VB.NET语言的扩展,它允许编写C#或者VB.NET代码,以与查询数据库相同的方式操作内存数据. L ...
- mvc ef LINQ to Entities 不识别方法“Int32 Parse(System.String)”,因此该方法无法转换为存储表达式。
private sys_User GetUserInfo() { sys_User model = null; var userId = Convert.ToInt32(AccountHelper.G ...
- Linq to entities 学习笔记
Linq to entities ---提供语言集成查询支持用于在概念模型中定义的实体类型. 首先可以根据http://msdn.microsoft.com/en-us/data/jj206878该 ...
随机推荐
- git报错 error: cannot stat ‘file’: Permission denied
切换分支时报错: error: cannot stat ‘file’: Permission denied 解决方法:退出编辑器.浏览器.资源管理器等,然后再切换就可以了.
- Retrofit源码设计模式解析(上)
Retrofit通过注解的方法标记HTTP请求参数,支持常用HTTP方法,统一返回值解析,支持异步/同步的请求方式,将HTTP请求对象化,参数化.真正执行网络访问的是Okhttp,Okhttp支持HT ...
- iOS之UI--辉光动画
前言:学习来自YouXianMing老师的博客:<辉光UIView的category>以及YouXianMing老师的github源码:< GlowView > 而我个人 ...
- 在MAC下搭建JSP开发环境
1.Mac下JDK的下载安装及配置 在安装jdk之后,需要为jdk安装目录配置环境变量: 任意打开终端,默认是家目录的,然后直接输入: touch .bash_profile 然后输入:vi .bas ...
- android基础开发之RecycleView(1)---基本使用方式
RecycleView是google为了优化listview,gridview 提供的一个新的控件. 1.android 导入recycleview 在app的gradle里面加入: dependen ...
- 一个不错的shell 脚本教程 入门级
一个很不错的bash脚本编写教程,至少没接触过BASH的也能看懂 建立一个脚本 Linux中有好多中不同的shell,但是通常我们使用bash (bourne again shell) 进行s ...
- linux指定账号下配置单独的jdk版本
1.下载tar.gz格式的安装包,上传到服务器,并解压,本例使用jdk-7u79-linux-i586.tar.gz 2.进入指定账户的目录下, vi .bashrc,添加环境变量并保存: ...
- fcntl 获取文件状态标志
int fcntl(int fd,int cmd,...) 函数fcntl提供了非常丰富的功能.主要依赖于cmd的各种参数: 复制已有的文件描述符 F_DUPFD,F_DUPFD_CLOEXEC 获取 ...
- Python HeapSort
__author__ = 'student' print 'hello world hello python' ''' heap sort root leftchild 2n+1 rightchild ...
- check the element in the array occurs more than half of the array length
Learn this from stackflow. public class test { public static void main(String[] args) throws IOExcep ...