How linq to sql works with sql connections?
What is the best way of working with linq data context? And how does lin开发者_Go百科k work with sql connection (when does it open connection and when does it close connection)? Should I aloways use using statement when i work with data context?
Sorry for list of questions. Thanks in advance.
There's a lot to cover here - I'll give you my potted view - and then give you some links etc to help you further.
There are many other similar questions around this site as well, though - so do a search and you'll find more.
Lifetime
You don't need to use a
using
statement with a Linq-To-Sql DataContext, but you do have to dispose it when you're done. Therefore the using block is the best way because of it's try ... finally {} semantics. So, in my opinion you should use ausing
block.You should not keep linq to sql data contexts open for long periods of time, because of the change tracking that occurs in every object that the context opens - it damages performances and can cause unexpected behaviour.
The Sql Connection, as far as I'm aware, is opened when the context is constructed, and closed when it is disposed.
Therefore, you should open a linq to sql context when you want to select, insert, update or delete data, and then close it once you're done. Inserting 100 records via the same DC is fine, for example; as is updating or deleting. However I probably wouldn't select a few thousand records of one type, update a few thousand of another, then delete some more of another all in one context - primarily for performance reasons.
Related Data
If you have related data - i.e. Table A -> Table B, then know that the default for the DataContext (DC) is to lazy-load a related row in B when accessed from the child property on A. Therefore, if you intend to pass back one of your linq to sql-generated classes outside of the code that creates and disposes the DC that is used to select, you can get ObjectDisposedException
s getting thrown.
To avoid this - you can use the DataLoadOptions.LoadWith<> and DataLoadOptions.AssociateWith<> to mitigate this also - which forces a pre-fetch of related rows when one row is selected. This can increase the amount of data that your Linq To Sql queries read from the database, though, so you would not typically always apply prefetches of all related records for all queries - only on those that you know will require them.
Sorry, I'm not giving code examples or anything else - there's a lot to cover in one answer - but here's some links:
Rick Strahl talking about Linq To Sql DC lifetimes
Dinesh of Microsoft talking about the same
Scott Guthrie - 9 Part Linq to SQL Series - this is a linq to a search on his blog - scroll down, and page through, and you'll find all of the different parts, starting with part 1 back in May 2007.
精彩评论