《Entity Framework 6 Recipes》中文翻译系列 (15) -----第三章 查询之与列表值比较和过滤关联实体

时间:2023-03-08 18:39:13

翻译的初衷以及为什么选择《Entity Framework 6 Recipes》来学习,请看本系列开篇

3-8与列表值比较

问题

  你想查询一个实体,条件是给定的列表中包含指定属性的值。

解决方案

  假设你有如图3-9所示的模型。

《Entity Framework 6 Recipes》中文翻译系列 (15) -----第三章 查询之与列表值比较和过滤关联实体

图3-9 包含books和它的categoryes的模型

  你想查找给定目录列表中的所有图书。在代码清单3-16中使用LINQ和Entity SQL来实现这上功能。

代理清单3-16. 使用LINQ和Entity SQL来查找给定目录列表中的所有图书

  using (var context = new EFRecipesEntities())
{
// 删除之前的测试数据
context.Database.ExecuteSqlCommand("delete from chapter3.book");
context.Database.ExecuteSqlCommand("delete from chapter3.category");
// 添加新的测试数据
var cat1 = new Category {Name = "Programming"};
var cat2 = new Category {Name = "Databases"};
var cat3 = new Category {Name = "Operating Systems"};
context.Books.Add(new Book {Title = "F# In Practice", Category = cat1});
context.Books.Add(new Book {Title = "The Joy of SQL", Category = cat2});
context.Books.Add(new Book
{
Title = "Windows 7: The Untold Story",
Category = cat3
});
context.SaveChanges();
} using (var context = new EFRecipesEntities())
{
Console.WriteLine("Books (using LINQ)");
var cats = new List<string> {"Programming", "Databases"};
var books = from b in context.Books
where cats.Contains(b.Category.Name)
select b;
foreach (var book in books)
{
Console.WriteLine("'{0}' is in category: {1}", book.Title,
book.Category.Name);
}
} using (var context = new EFRecipesEntities())
{
Console.WriteLine("\nBooks (using eSQL)");
var esql = @"select value b from Books as b
where b.Category.Name in {'Programming','Databases'}";
var books = ((IObjectContextAdapter) context).ObjectContext.CreateQuery<Book>(esql);
foreach (var book in books)
{
Console.WriteLine("'{0}' is in category: {1}", book.Title,
book.Category.Name);
}
} Console.WriteLine("\nPress <enter> to continue...");
Console.ReadLine();
}

代码清单3-16的输出如下:

Books (using LINQ)
'F# In Practice' is in category: Programming
'The Joy of SQL' is in category: Databases
Books (using ESQL)
'F# In Practice' is in category: Programming
'The Joy of SQL' is in category: Databases

原理

  在LINQ查询中,我构造了一个简单的目录名列表,它使用LINQ查询操作符Contains。细心的读者可以注意了,我使用cats集合,并判断它是否包含某一目录名。实体框架将Containts从句转换成SQL语句中的in从句。如代码清单3-17所示:

代码清单3-17.  代码清单3-16中LINQ查询表达式对应的SQL语句

 SELECT
[Extent1].[BookId] AS [BookId],
[Extent1].[Title] AS [Title],
[Extent1].[CategoryId] AS [CategoryId]
FROM [chapter3].[Books] AS [Extent1]
LEFT OUTER JOIN [chapter3].[Category] AS [Extent2] ON [Extent1].[CategoryId] = [Extent2].[CategoryId]
WHERE [Extent2].[Name] IN (N'Programming',N'Databases')

  有趣的是,代码清单3-17中的SQL语句,没有为从句的项使用参数。 这不同于LINQ to SQL中产生的代码,列表中的项会被参数化。超过SQL Server的参数限制的风险,会使代码不能运行。

  如果我们需要查找出给定目录列表中的所有书,列表目录中包含未分类的目录,我们只需在目录列表中简单地使用null值。产生的SQL语句,如代码清单3-18所示。

代码清单3-18.代码清单3-16中LINQ查询表达式对应的SQL语句,但是目录列表中多了一上null值。

 SELECT
[Extent1].[BookId] AS [BookId],
[Extent1].[Title] AS [Title],
[Extent1].[CategoryId] AS [CategoryId]
FROM [chapter3].[Books] AS [Extent1]
LEFT OUTER JOIN [chapter3].[Category] AS [Extent2] ON [Extent1].[CategoryId] = [Extent2].[CategoryId]
WHERE [Extent2].[Name] IN (N'Programming',N'Databases')
OR [Extent2].[Name] IS NULL

  相同地,我们包含了一个使用Entity SQL的查询版本,它显式地包含了一个SQL IN 从句。

3-9过滤关联实体

问题

  你想获取一部分,不是全部关联实体。

解决方案

  假设你有如图3-10所示的模型。

《Entity Framework 6 Recipes》中文翻译系列 (15) -----第三章 查询之与列表值比较和过滤关联实体

图3-10 包含Worker和他们的Accidents的模型

  在模型中,一个Worker有零个或是多个accidents.每个事故按严重性分类,我们要获取所有的工人,对于与之关联的事故,只对严重事故感兴趣,事故的严重性大于2.

  在示例中我们使用了Code-First,在代码清单3-19中,创建了实体类Worker和Accidentd.

代码清单3-19. 实体类

  public class Worker
{
public Worker()
{
Accidents = new HashSet<Accident>();
} public int WorkerId { get; set; }
public string Name { get; set; } public virtual ICollection<Accident> Accidents { get; set; }
} public class Accident
{
public int AccidentId { get; set; }
public string Description { get; set; }
public int? Severity { get; set; }
public int WorkerId { get; set; } public virtual Worker Worker { get; set; }
}

  接下来,我们在代码清单3-20中创建Code-First中使用的上下文对象。

代码清单3-20. 上下文对象

 public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("ConnectionString") {} public DbSet<Accident> Accidents { get; set; }
public DbSet<Worker> Workers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Accident>().ToTable("Chapter3.Accident");
modelBuilder.Entity<Worker>().ToTable("Chapter3.Worker");
base.OnModelCreating(modelBuilder);
}
}

  使用代码清单3-21中的模式,获取所有的worders,和严重事故。

代码清单3-21 使用CreateSourceQuery和匿名类型获取严重事故

 using (var context = new EFRecipesEntities())
{
// 删除之前的测试数据
context.Database.ExecuteSqlCommand("delete from chapter3.accident");
context.Database.ExecuteSqlCommand("delete from chapter3.worker");
// 添加新的测试数据
var worker1 = new Worker { Name = "John Kearney" };
var worker2 = new Worker { Name = "Nancy Roberts" };
var worker3 = new Worker { Name = "Karla Gibbons" };
context.Accidents.Add(new Accident
{
Description = "Cuts and contusions",
Severity = ,
Worker = worker1
});
context.Accidents.Add(new Accident
{
Description = "Broken foot",
Severity = ,
Worker = worker1
});
context.Accidents.Add(new Accident
{
Description = "Fall, no injuries",
Severity = ,
Worker = worker2
});
context.Accidents.Add(new Accident
{
Description = "Minor burn",
Severity = ,
Worker = worker2
});
context.Accidents.Add(new Accident
{
Description = "Back strain",
Severity = ,
Worker = worker3
});
context.SaveChanges();
} using (var context = new EFRecipesEntities())
{
// 显式禁用延迟加载
context.Configuration.LazyLoadingEnabled = false;
var query = from w in context.Workers
select new
{
Worker = w,
Accidents = w.Accidents.Where(a => a.Severity > )
};
query.ToList();
var workers = query.Select(r => r.Worker);
Console.WriteLine("Workers with serious accidents...");
foreach (var worker in workers)
{
Console.WriteLine("{0} had the following accidents", worker.Name);
if (worker.Accidents.Count == )
Console.WriteLine("\t--None--");
foreach (var accident in worker.Accidents)
{
Console.WriteLine("\t{0}, severity: {1}",
accident.Description, accident.Severity.ToString());
}
}
} Console.WriteLine("\nPress <enter> to continue...");
Console.ReadLine();
}

下面是代码清单3-21的输出:

Workers with serious accidents...
John Kearney had the following accidents
Cuts and contusions, severity:
Broken foot, severity:
Nancy Roberts had the following accidents
Minor burn, severity:
Karla Gibbons had the following accidents
--None--

原理

  正如你在随后的第五章中看到的那样,我们需要立即加载一个关联集合,我们经常使用Include()方法和一个查询路径。(Include()方法在单个查询中返回父对象和所有的子对象)。然后,Include()方法不允许过滤关联的子实体对象,在本节中,我们展示了,通过轻微的改变,让你可以加载并过滤相关联的子实体对象。

  在代码块中,我们创建了一些workers,并分配给它们相关的不同等级的accidents。不得不承认,分配事故给人,有点毛骨悚然!但,这只是为了得到一些可以让我们继续工作的数据。

  在随后的查询中,我们获取所有的工人并将结果投射到匿名对象上,这个类型包含了一个worker和一个accidents集合。对于accidents,应该注意,我们是如何过滤集合,只获取严重事故的。

  接下来的一行,非常重要!(译注:也就是query.ToList();),我们通过调用ToList()方法,强制查询求值。(记住,LINQ查询默认为延迟加载。意思是,直到结果被使用时,查询才被真正地执行。ToList()方法能强制查询执行)。在Dbcontext(译注:其实是它的子类EFRecipesEntities)中枚举所有的工人和所有的相关的严重事故。 匿名类型不会把accidents附加到workers上,但是通过把它们带到上下文中,实体框架会填充导航属性,将每一个严重事故集合accidents附加到合适的worker上。这个过程一般叫做:Entity Span。这是一个强大而微妙的,发生在实体框架实例化实体类型及它们之间关系的幕后的副作用。

  我们关闭了延迟加载,以便让accidents在我们的过滤查询中加载(我们将在第5章讨论延迟加载)。如果打开延迟加载,所有的accidents将在我们引用worker的accidents时才加载。这将导致过虑失败。

  我们一旦有了结果集合,就可以枚举并打印出每个worker和它的accidents信息。如果一个worker没有任何严重的accidents,我们打印none来指示他们的安全记录。

  

实体框架交流QQ群:  458326058,欢迎有兴趣的朋友加入一起交流

谢谢大家的持续关注,我的博客地址:http://www.cnblogs.com/VolcanoCloud/