实体框架查询

1.查询
private static void FindGreatBarrierReef()
{
using (var context = new BreakAwayContext())
{
var query = from d in context.Destinations
where d.Name == "Great Barrier Reef"
select d;
var reef = query.SingleOrDefault();
if (reef == null)
{
Console.WriteLine("Can't find the reef!");
}
else
{
Console.WriteLine(reef.Description);
}
}
}
2.需要记住的非常重要的是:所有的面向DbSet的查询都是从数据库中查找数据
One important thing to remember is that LINQ queries against a DbSet always send a
query to the database to find the data.
到目前为止通过LinQ去直接查询DbSet,这将导致直接对数据库发出SQL语句。
So far you’ve used LINQ to query a DbSet directly, which always results in a SQL query
being sent to the database to load the data.
3.Find方法:从内存中以及数据库中根据主键来查找
4.通过访问DbSet的Local属性可以访问本地存储的对象
eg:
private static void GetLocalDestinationCount()
{
using (var context = new BreakAwayContext())
{
foreach (var destination in context.Destinations)
{
Console.WriteLine(destination.Name);
}
var count = context.Destinations.Local.Count;//获取本地对象的数量
Console.WriteLine("Destinations in memory: {0}", count);
}
}
5.通过循环便利DbSet的某个属性可以将数据库中的数据加载到内存中,但是效率比较低。幸运的是DbContext API包含了 Load方法,
这样可以将数据库中的数据加载到内存中去。
Fortunately the DbContext API includes a Load method, which can be used on a
DbSet to pull all the data from the database into memory.
eg:
private static void GetLocalDestinationCountWithLoad()
{
using (var context = new BreakAwayContext())
{
context.Destinations.Load();
var count = context.Destinations.Local.Count;
Console.WriteLine("Destinations in memory: {0}", count);
}
}
*注意Load方法是 IQueryable<T> 的扩展方法,所以想使用的话必须引入System.Data.Entity在这个名称空间。
 
6.因为 Load 是IQueryable<T>的扩展方法,我们也可以通过这个方法来加载数据到内存代替的是从dbset中获取
eg: Loading results of a LINQ query into memory
private static void LoadAustralianDestinations()
{
using (var context = new BreakAwayContext())
{
var query = from d in context.Destinations
where d.Country == "Australia"
select d;
query.Load();
var count = context.Destinations.Local.Count;
Console.WriteLine("Aussie destinations in memory: {0}", count);
 
7.执行LinQ从本地对象中进行查询
Example 2-21. Using LINQ to query Local
private static void LocalLinqQueries()
{
using (var context = new BreakAwayContext())
{
context.Destinations.Load();//加载数据到本地
 
var sortedDestinations = from d in context.Destinations.Local
orderby d.Name
select d;//从本地数据中查询数据 按照某些条件进行排序
Console.WriteLine("All Destinations:");
 
foreach (var destination in sortedDestinations)
{
	Console.WriteLine(destination.Name);
}
 
var aussieDestinations = from d in context.Destinations.Local
where d.Country == "Australia"
select d;//从本地查找数据 加上了 某些条件
Console.WriteLine();
Console.WriteLine("Australian Destinations:");
foreach (var destination in aussieDestinations)
{
Console.WriteLine(destination.Name);
}
}
 
8.Querying against DbSet uses LINQ to Entities:查询dbset是用的Linq to entities
However, querying against Local uses LINQ to Objects:然而查询Local是利用Linq to objects
9.Local will raise the CollectionChanged event whenever the contents of Local change。
Local将会发起集合变更事件,当集合内容变更时。
10.ObservableCollection<T>:集合内容变更时允许订阅者订阅事件。事件也会通知订阅人。
eg:
private static void ListenToLocalChanges()
{
using (var context = new BreakAwayContext())
{
context.Destinations.Local
.CollectionChanged += (sender, args) =>
{
if (args.NewItems != null)
{
foreach (Destination item in args.NewItems)
{
Console.WriteLine("Added: " + item.Name);
}
}
if (args.OldItems != null)
{
foreach (Destination item in args.OldItems)
{
Console.WriteLine("Removed: " + item.Name);
}
}
};
context.Destinations.Load();
}
}
11.查询和一个对象相关联的数据通常有三种方式:1懒加载 2立即加载 3按需要加载
 懒加载:
 (1).Your POCO class must be public and not sealed.PoCO类必须是public并且可以继承。
 (2)The navigation properties that you want to be lazy loaded must also be marked as
virtual so that Entity Framework can override theproperties to include the lazy loading logic.
相关联的实体的方法必须是virtual虚方法,这样实体框架可以重写这些属性为了实现懒加载逻辑。
如果不满足条件,那么和这个对象相关联的其他对象就不会自动的填充值。
12.如何禁用懒加载:If you decide that lazy loading is just too much magic, you can choose
to disable it altogether by using the DbContext.Configuration.LazyLoa
dingEnabled property.
13.通过Include来立即加载关联数据
eg:
private static void TestEagerLoading()
{
using (var context = new BreakAwayContext())
{
	var allDestinations = context
		.Destinations
		.Include(d => d.Lodgings);//查询Destination的时候关联查询Lodgings
	foreach (var destination in allDestinations)
	{
		Console.WriteLine(destination.Name);
		foreach (var lodging in destination.Lodgings)
		{
			Console.WriteLine(" - " + lodging.Name);
		}
	}
}
14.多关联查询数据
eg:级联查询
What if you want to query for Destinations
and include Lodgings and also the PrimaryContact for each of the related Lodging instances?
context.Destinations
.Include(d => d.Lodgings.Select(l => l.PrimaryContact))
eg:这个类和多个类关联
context.Lodgings
.Include(l => l.PrimaryContact)
.Include(l => l.SecondaryContact)
 
15.明确加载
 1)明确加载是通过DbContext.Entry 方法来实现的,这个Entry方法告诉你与实体相关的所有的信息。
 2)通过这个方法不仅能够获取到实体的值的属性,而且可以获取实体状态以及原始值信息。
 3)这个类还提供了获取相关关系的方法。
 eg:
 private static void TestExplicitLoading()
{
using (var context = new BreakAwayContext())
{
var query = from d in context.Destinations
where d.Name == "Grand Canyon"
select d;
var canyon = query.Single();//IQueryable
context.Entry(canyon)//获取实体
.Collection(d => d.Lodgings)//Collection and Reference 通过lambda 表达式来指定要加载数据的。
.Load();//明确要查询的关联数据
Console.WriteLine("Grand Canyon Lodging:");
foreach (var lodging in canyon.Lodgings)
{
Console.WriteLine(lodging.Name);
}
}
}
16 明确加载,加载相关对象时通过某些条件来加载
eg:
private static void QueryLodgingDistance()
{
using (var context = new BreakAwayContext())
{
var canyonQuery = from d in context.Destinations
where d.Name == "Grand Canyon"
select d;
var canyon = canyonQuery.Single();
 
var lodgingQuery = context.Entry(canyon)
.Collection(d => d.Lodgings)
.Query();//在这里创建一个查询
 
var distanceQuery = from l in lodgingQuery
where l.MilesFromNearestAirport <= 10//将条件加入的查询的条件中去
select l;
 
 
foreach (var lodging in distanceQuery)
{
Console.WriteLine(lodging.Name);
}
 
var lodgingCount = distanceQuery.Count();//直接获取数量
 
}
}
 
context.Entry(canyon)
.Collection(d => d.Lodgings)
.Query()
.Where(l => l.Name.Contains("Hotel"))//查询相关的条件
.Load();//然后Load
 
posted @ 2013-10-31 00:22  feidaochuanqing  阅读(339)  评论(0编辑  收藏  举报