Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL eager loading with conditions

I'm trying to learn LINQ to SQL and i've found out about the LoadWith function. All the examples i've found will load all records from the table you specify in the LoadWith function e.g.

var dlo = new DataLoadOptions();
dlo.LoadWith<Blog>(b => b.Posts);
this.LoadOptions = dlo;

What I would like to know is if it's possible to load in this example only the last blog post?

I've tried

dlo.LoadWith<Blog>(b => b.Posts.Max());

But it doesn't like that syntax.

like image 571
Alex Avatar asked Apr 02 '09 14:04

Alex


People also ask

Is LINQ lazy loading?

In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

Is Eager Loading better than lazy loading?

Lazy Loading vs. Eager Loading. Eager loading generates all web page content as soon as possible, while lazy loading delays the display of non-essential content. Lazy loading is a great option for large page files with more content.

Is IQueryable lazy loading?

IQueryable supports deferred execution. IQueryable supports custom query using CreateQuery and Execute methods. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.

What is difference between IEnumerable and IQueryable?

The major difference between IQueryable and IEnumerable is that IQueryable executes query with filters whereas IEnumerable executes the query first and then it filters the data based on conditions.


2 Answers

You can do it using AssociateWith. This will work:

var options = new DataLoadOptions();
options.AssociateWith<Blog>(b => 
    b.Posts.Where(
        p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
    ));

Also, if you will be loading the info into a separate class or can use an anonymous one you can just do the query as:

var query = from b in context.Blogs
            //probably some where you already have
            select new MyBlogs // or with no type in case it is anonymous
            {
                AColumn = b.AColumn, //map any other values
                LatestPost = b.Posts.Where(
                      p1 => p1.SomeColumn == b.Posts.Max(p2 => p2. SomeColumn)
                  )).ToList()
            }
like image 182
eglasius Avatar answered Sep 20 '22 22:09

eglasius


If you only want the last post then I suspect that simply querying for that post specifically will be more efficient using lazy loading than forcing an 'eager' load this way.

like image 38
Lazarus Avatar answered Sep 17 '22 22:09

Lazarus