您的位置:首页 > 数据库 > MySQL

Entity Framework with MySQL 学习笔记一(查询)

2014-09-27 23:49 441 查看
参考 : http://msdn.microsoft.com/en-us/data/jj574232.aspx
EF 查询基本上有3中

默认是 Lazy Loading

特色是只有在需要数据的时候EF才会像数据库请求,它不会使用任何inner join

比如我们有一个产品,有很多颜色,(1对多)

那么我们想把每个产品和颜色统统选出来

using (EFDB db = new EFDB())
{
var prods = db.prods.ToList(); //像数据库请求prods, 但是不会包括colors
foreach (var prod in prods)
{
var color = prod.colors; //每一次都像数据库请求颜色
}
}


首先必须用 ToList(),不然之后的 prod.colors是会报错的。

如果prods有很多,它会发出很多次请求,这对性能是有影响的!

Opened connection at 2014/9/27 23:47:13 +08:00
SELECT
`Extent1`.`id`,
`Extent1`.`code`,
`Extent1`.`name`
FROM `prod` AS `Extent1`
-- Executing at 2014/9/27 23:47:13 +08:00
-- Completed in 13 ms with result: EFMySqlDataReader

Closed connection at 2014/9/27 23:47:13 +08:00
Opened connection at 2014/9/27 23:47:15 +08:00
SELECT
`Extent1`.`id`,
`Extent1`.`color`,
`Extent1`.`prod_id`
FROM `prod_color` AS `Extent1`
WHERE `Extent1`.`prod_id` = @EntityKeyValue1
-- EntityKeyValue1: '1' (Type = Int32, IsNullable = false)
-- Executing at 2014/9/27 23:47:15 +08:00
-- Completed in 13 ms with result: EFMySqlDataReader

Closed connection at 2014/9/27 23:47:15 +08:00
Opened connection at 2014/9/27 23:47:17 +08:00
SELECT
`Extent1`.`id`,
`Extent1`.`color`,
`Extent1`.`prod_id`
FROM `prod_color` AS `Extent1`
WHERE `Extent1`.`prod_id` = @EntityKeyValue1
-- EntityKeyValue1: '2' (Type = Int32, IsNullable = false)
-- Executing at 2014/9/27 23:47:17 +08:00
-- Completed in 13 ms with result: EFMySqlDataReader

Closed connection at 2014/9/27 23:47:17 +08:00
Opened connection at 2014/9/27 23:47:17 +08:00
SELECT
`Extent1`.`id`,
`Extent1`.`color`,
`Extent1`.`prod_id`
FROM `prod_color` AS `Extent1`
WHERE `Extent1`.`prod_id` = @EntityKeyValue1
-- EntityKeyValue1: '3' (Type = Int32, IsNullable = false)
-- Executing at 2014/9/27 23:47:17 +08:00
-- Completed in 13 ms with result: EFMySqlDataReader

Closed connection at 2014/9/27 23:47:17 +08:00
Opened connection at 2014/9/27 23:47:17 +08:00
SELECT
`Extent1`.`id`,
`Extent1`.`color`,
`Extent1`.`prod_id`
FROM `prod_color` AS `Extent1`
WHERE `Extent1`.`prod_id` = @EntityKeyValue1
-- EntityKeyValue1: '4' (Type = Int32, IsNullable = false)
-- Executing at 2014/9/27 23:47:17 +08:00
-- Completed in 14 ms with result: EFMySqlDataReader

Closed connection at 2014/9/27 23:47:17 +08:00


View Code

原始方法调用 select

using (DB db = new DB())
{
List<Color> colors = db.Database.SqlQuery<Color>("select * from color where id in ({0})",10).ToList();
}


也是用了很多的查询...

目前我还没有找到比较可以接受的查询方式。至少我觉得对性能有点要求的人应该不会使用上面任何一种方法吧..

继续专研...待续
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: