简体   繁体   中英

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 eg

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.

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()
            }

如果你只想要最后一篇文章,那么我怀疑只使用延迟加载查询该帖子比使用这种方式强制'急切'加载更有效。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM