LINQ到SQL立即加载与条件 [英] LINQ to SQL eager loading with conditions

查看:135
本文介绍了LINQ到SQL立即加载与条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我努力学习LINQ to SQL和我已经发现了关于LoadWith功能。我所发现的例子将加载的所有记录您在LoadWith的功能,例如指定表

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?

我试过

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

不过,这并不喜欢这种语法。

But it doesn't like that syntax.

推荐答案

您可以使用AssociateWith做到这一点。这将工作:

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

这篇关于LINQ到SQL立即加载与条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆