LINQ到SQL立即加载与条件加载、条件、LINQ、SQL

2023-09-04 02:43:45 作者:凉辰梦瑾空人心。

我努力学习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()
            }