lambda表达式Expression> 、Func区别 Entity Framework - Func引发的数据库全表查询

前言:html

本身经过lambda表达式的封装,将对应的表达式转成字符串的过程当中,对lambda表达式有了新的认识数据库

缘由:express

不少开发者对lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>表示存在疑惑,如今就用代码举个简单列子post

 

 

 

 原代码:优化

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;url

namespace Lambda
{
class Program
{
static void Main(string[] args)
{
Expression<Func<Person, bool>> exp = null;spa

Func<Person, string> func = null;
func = p => { return p.age; };htm

exp = p => p.sex=="男";blog

Person person = new Person();
person.age = "12";
person.name = "zouhp";
person.sex = "男";开发

Console.WriteLine(exp);
Console.WriteLine(exp.Compile()(person));
Console.WriteLine(func(person));
Console.ReadLine();
}
public class Person
{
public string name;
public string age;
public string sex;
}
}
}

 

结论:

Func<TObject, bool>是委托(delegate)

Expression<Func<TObject, bool>>是表达式

Expression编译后就会变成delegate,才能运行。好比

Expression<Func<int, bool>> ex = x=>x < 100;

Func<int, bool> func = ex.Compile(); 

而后你就能够调用func:

func(5) //-返回 true

func(200) //- 返回 false

而表达式是不能直接调用的。

参考:http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct

 

关于EF中用哪一个你能够看看这篇文章:Entity Framework - Func引发的数据库全表查询

关于如何将多个expression合并为一个能够写多个where:

.where(expression1).where(expression2)...

运行时EF会自动合并优化的

相关文章
相关标签/搜索