LINQ to SQL ÐÔÄÜ 10 Tips
LINQ to SQL ÐÔÄÜ 10 Tips
http://www.cnblogs.com/worksguo/archive/2008/06/04/1213075.html
ǰһÖÜ£¬ÎÒµÄÓ²ÅÌÓÐÁ½·ÖÇø»µÁË£¬ÎÒ×¼±¸µÄÎÄÕÂÓë×ÊÁ϶¼ÔÚÀïÃæ£¬ËùÒÔLINQµÄÎÄÕÂÍ£ÁËÒ»¶Îʱ¼ä£¬ÕæµÄÌ«²»ºÃÀ£¬ÎªÀ´ÃÖ²¹Ò»Ï¾ÍÏÈ·¢ÕâÆªÎÄÕÂÉÏÀ£¬Ã÷ÌìÔÙһƪ¹ØÓÚDisconnection DataµÄÎÄÕ¡£
Ö»²»¹ýÐҺã¬ÔÚÕ⼸ÌìÖÐÎҽ߾¡È«Á¦»Ö¸´ÕâЩÊý¾Ý£¬¾¹ý3ÌìµÄŬÁ¦ÖÕÓÚÊÇÈ«²¿ÕÒ»ØÀ´À¡£
ÏÂÃæÊÇһЩÌÖÂÛLINQ to SQLÐÔÄÜһЩÎÄÕ¡£
http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx
http://www.jdconley.com/blog/archive/2007/11/28/linq-to-sql-surprise-performance-hit.aspx
"LINQ Changes How You Will Program" by Bill McCarthy.
"Layer Data Access with LINQ to SQL" by Roger Jennings.
1:¹Ø±ÕOjectTrackingEnabledÊôÐÔ.
Èç¹ûÄãÖ»ÊÇÕÒ»ØÊý¾Ý,²¢ÇÒ²»ÐÞ¸ÄÈκζ«Î÷,Äã²»ÐèÒªobjectTracking,ËùÓоÍÏñÏÂÃæÒ»Ñù:
using (NorthwindDataContext context = new NorthwindDataContext())
{
context.ObjectTrackingEnabled = false;
}
2:²»Òª½«ÄãµÄËùÓÐDB Object¶¼·ÅÈëµ¥¸öDataContextÖÐ.
DataContext±íʾһ¸öµ¥¶ÀµÄ¹¤×÷µ¥Ôª,¶ø²»ÊÇÄãÊý¾Ý¿âÈ«²¿.ÈçÈôÄãÓжà¸öûÓÐÁ¬½ÓµÄÊý¾Ý¿â¶ÔÏó,»òËûÃÇûÓб»Ê¹ÓÃ.ÕâЩ¶ÔÏó¾Í²»ÐèÒªÌí¼Ó½øÄÚ´æÖеıêʶ¹ÜÀíÖÐÏûºÄµÄÄÚ´æ¿Õ¼äºÍÔÚDataContextµÄCUD engine¸ú×Ù¶ÔÏóµÄ»¨·Ñ.
ÎÒ½¨ÒéÄ㽫ÄãµÄ¹¤×÷Êý¾ÝÇøÓò·Ö¸î¼¸¸öDataContexts,ÿһ¸öÇøÓò±íʾһ¸öµ¥¶ÀµÄʹÓÃÊý¾ÝµÄ¹¤×÷µ¥Ôª.Ä㻹ÊÇÄÜʹÓÃͬһ¸öÁ¬½Ó.
3:²»ÒªÊ¹Óà CompiledQuery
µ±Äã´´½¨ºÍÖ´ÐÐÄãµÄ²éѯ,´Óexpressionµ½ÏàÓ¦µÄSQL,Óм¸¸ö²½Öè:
1.
Create expression tree(´´½¨±í´ïÊ÷)
2.
Convert it to SQL(ת»»SQL)
3.
Run the query(ÔËÐвéѯ)
4.
Retrieve the data(ÕÒ»ØÊý¾Ý)
5.
Convert it to the objects(ת»»Îª¶ÔÏó)
Äã×¢Òâ:µ±ÄãʹÓÃÒ»´ÎÒ»´ÎʹÓÃͬһ¸ö²éѯʱ,µÚÒ»ºÍµÚ¶þ²½ÊÇ×îºÄ·Ñʱ¼ä.
ÕâÀïÒªÉÙʹÓÃÓÃÀ´CompiledQueryµÄÔÚSystem.Data.Linq ÃüÃû¿Õ¼äÖеÄÀà,ʹÓÃCompiledQuery,ÄãÒ»´Î±àÒëÄãµÄ²éѯ²¢ÇÒ´æ´¢ËüÔÚÖ®ºóʹÓõĵط
Ïà¹ØÎĵµ£º
1) ͳ¼Æ¸÷¸öϵµÄѧÉúÐÅÏ¢
select count(Sname) ×ÜÈËÊý,Sdept from Student group by Sdept
2) ²éѯÐŹÜϵѧÉúµÄ×î´óÄêÁäºÍ×îСÄêÁä
select MAX(Sage) ×î´óÄêÁä,MIN(Sage) ×îСÄêÁä from Student where
Sdept='ÐŹÜϵ'
3) ²éѯÐŹÜϵ×î´óÄêÁäºÍ×îСÄêÁäµÄѧÉúµÄÐÕÃû
select Sname from St ......
--ÈÕÆÚת»»²ÎÊý,ÖµµÃÊÕ²Ø
select CONVERT(varchar, getdate(), 120 )2004-09-12 11:06:08
select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','')20040912110608
select CONVERT(varchar(12) , getdate(), 111 )2004/09/12
select CONVERT(varchar(12) , getdate(), 112 )20040912 ......
ÏÂÁÐÓï¾ä²¿·ÖÊÇMssqlÓï¾ä£¬²»¿ÉÒÔÔÚaccessÖÐʹÓá£
SQL·ÖÀࣺ
DDL—Êý¾Ý¶¨ÒåÓïÑÔ(CREATE£¬ALTER£¬DROP£¬DECLARE)
DML—Êý¾Ý²Ù×ÝÓïÑÔ(SELECT£¬DELETE£¬UPDATE£¬INSERT)
DCL—Êý¾Ý¿ØÖÆÓïÑÔ(GRANT£¬REVOKE£¬COMMIT£¬ROLLBACK)
Ê×ÏÈ,¼òÒª½éÉÜ»ù´¡Óï¾ä£º
1¡¢ËµÃ÷£º´´½¨Êý¾Ý¿â
CREATE DATABASE data ......
1. GROUP BY ÊÇ·Ö×é²éѯ, Ò»°ã GROUP BY ÊǺ;ۺϺ¯ÊýÅäºÏʹÓÃ
group by ÓÐÒ»¸öÔÔò,¾ÍÊÇ select ºóÃæµÄËùÓÐÁÐÖÐ,ûÓÐʹÓþۺϺ¯ÊýµÄÁÐ,±ØÐë³öÏÖÔÚ group by ºóÃæ£¨ÖØÒª£©
ÀýÈç,ÓÐÈçÏÂÊý¾Ý¿â±í£º
A B
1 abc
1 bcd
1 asdfg
Èç¹ûÓÐÈ ......
ÔÚLINQ to EntitiesÖÐûÓа취ÔÙÏñ LINQ to SQL ÖÐÒ»ÑùʹÓà Contains µÄ·½·¨À´ÊµÏÖsql "in" ¹Ø¼ü×Ö
ÏÂÃæ´úÂëÔÚ LINQ to SQL ÖпÉÐÐ ÔÚLINQ to EntitiesÈ´ÎÞ·¨ÔËÐУº
var s = db.Account.Select(c => c.ID);
var ret =(from t in db.Profile
where&n ......