LINQ to Everything

Charlie Calvert has a very valuable list of LINQ to <insert here> list

These are all LINQ implemented providers.

Quite a list!  LINQ has been something I’ve enjoyed working with.

I did learn recently on a side note that you can string together LINQ to SQL queries, that when get execute are treated as one query.

ie.

var cars = from p in dc.Cars where p.Model == "Focus";

var fordFocus = from c in cars where c.OwnerName = "Steve";

List<Cars> results = fordFocus.toList<Cars>();

This will create a joined sql query (ie. sql in statement) when executed as one query, not two separate database calls.

something like:

SELECT … FROM Cars WHERE ModelType IN (SELECT … FROM OwnerList WHERE OwnerId=Steve) 

Why is this? The query is not constructed until you attempt to enumerate through the results.  This is very key to understanding your queries in LINQ.

On a side note, I did have a need to force eager loading in LINQ to SQL.  The reason: by default it is set to lazyload.  But in my case, I wanted to get a master-detail loaded after I closed the DataContext.  If you attempt to lazyload after you have closed the DataContext, it won’t be able.

Code snippet:

using (FSDALDataContext dc = GetContext())
            {
                DataLoadOptions loadOption = new DataLoadOptions();
                loadOption.LoadWith<Campaign>(cp => cp.TargetsDestroyeds);
                dc.LoadOptions = loadOption;

                Campaign campaign = dc.Campaigns.Single(c => c.CampaignId == campaignId);

                return campaign;
            }

So, I’ve told it to go ahead and load the list of ‘targetsdestroyed’ when I retrieve a ‘campaign’.

(This is a one to many in my table structure)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s