繁体   English   中英

Linq包含和Where子句

[英]Linq Include and Where Clause

我有以下linq声明:

var result = _context.Settings
                     .Include(x => x.Files)
                     .Where(y => y.Files.Where(f => f.SettingFile == true))
                     .Select(z => z.Deleted == null)
                     .ToList();

我想要做的是从表中获取所有设置。 我还想包含files-table并获取具有SettingFile true的所有文件。 但我一直得到以下错误:

不能将IEnumerable(UploadedFile)类型转换为bool。

这是我的UploadedFile模型:

[Required]
public string FileName { get; set; }
[Required]
public string FileExtension { get; set; }
[Required]
public byte[] FileContent { get; set; }

public Guid? FormAnswerId { get; set; }
public Guid? LicenseHolderId { get; set; }
public Guid? CaseId { get; set; }
public Guid? ErrandId { get; set; }
public bool SettingFile { get; set; }

这是我的设置模型:

    public class Setting : ModelBase
{
    public string Key { get; set; }
    public string DisplayName { get; set; }
    public string DisplayText { get; set; }
    public string DisplayTab { get; set; }
    public string Value { get; set; }
    public string Type { get; set; }
    public virtual ICollection<UploadedFile> Files { get; set; }
}

模型库:

public abstract class ModelBase : EntityBase
{
   public DateTime? Deleted {get; set;}
}

我的查询错误是什么?

我不太明白你想要完成什么,但我可以解释你的问题。

Where()子句是Func<T, bool> 传入T的实例,它返回一个bool值。

在这一行.Where(y => y.Files.Where(f => f.SettingFile == true)) ,你将返回一个IEnumerable<T> ,它应该返回一个bool 这就是造成错误的原因。 您可以通过将y.Files.Where(f => f.SettingFile == true)更改为y.Files.Any(f => f.SettingFile)y.Files.All(f => f.SettingFile) 但是,我不认为这是你想要完成的。

编辑:由于您尝试获取具有SettingFile == true所有设置,因此请执行以下操作:

_context.Settings
        .Include(x => x.Files.Where(f => f.SettingFile == true))
        .Select(z => z.Deleted == null)
        .ToList();

编辑:在评论中进一步沟通后,你说你想要一个Setting集合。 所以你只需要删除.Select(x => z.Deleted == null) ,你应该是金色的。

_context.Settings
        .Include(x => x.Files.Where(f => f.SettingFile == true))
        .ToList();

我不知道您的用例,但建议添加另一个Where条件以排除任何没有SettingFiletrue Files Settings

_context.Settings
        .Include(x => x.Files.Where(f => f.SettingFile == true))
        .Where(x => x.Files.Any(f => f.SettingFile == true))
        .ToList();

暂无
暂无

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

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