简体   繁体   English

Linq条件包含

[英]Linq Conditional Include

I am trying to find the most efficient way to solve this problem: 我正在尝试找到解决此问题的最有效方法:

I am retrieving a File from the database. 我正在从数据库中检索文件。 If the FileSize is less than 10MB I want to include the FileContent, otherwise that will be left null. 如果FileSize小于10MB,我想包含FileContent,否则将保留为null。 My code as of right now is: 到目前为止,我的代码是:

var z = QuerySet.AsQueryable();

File f = z.FirstOrDefault(item => item.Id == id && item.FileSize >= 1024 * 1024 * 10);

if (f != null) return f;

return z.Include(a => a.FileContent)
    .FirstOrDefault(item => item.Id == id);

So, I query to find if it is my file (matched Id) and if it is a big file. 因此,我查询以查找它是否是我的文件(匹配的ID)以及它是否是一个大文件。 If so, return the file. 如果是这样,请返回文件。 Otherwise do the query again, but include the file content. 否则,请再次执行查询,但要包含文件内容。 Is there a more efficient way to accomplish this? 有没有更有效的方法来实现这一目标?

How about: 怎么样:

var item = z.Select(x => new {
        File = x,
        Content = x.FileSize >= sizeLimit ? null : x.FileContent
    }).FirstOrDefault(x => x.File.Id == id);

return item.File;

Should make the trick, but you'd have to confirm by looking at generated SQL. 应该可以解决问题,但是您必须通过查看生成的SQL进行确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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