【问题标题】:Select query on sub table在子表上选择查询
【发布时间】:2018-04-12 21:19:24
【问题描述】:

我正在编写一个基本的 CRM 来获取潜在客户。

您可以为潜在客户添加注释。

我想返回最近两天内没有备注的潜在客户列表。

我无法计算出启用此功能的 linq 查询。

到目前为止,我有以下内容将返回所有潜在客户而无需备注。

vm.LeadsNoNotes = _context.Lead.Include(x => x.Notes).Where(x => x.Notes.Count == 0).Take(10).ToList();

下面是我的模型结构

public class Lead
{
    public int LeadId { get; set; }
    public DateTime? DateCreated { get; set; }
    public DateTime? DateModified { get; set; }

    public string Name { get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }

    public string Comment { get; set; }

    public string Status { get; set; }

    public string Source { get; set; }

    public string PreferedContactMethod { get; set; }

    public string Vehicle { get; set; }

    public List<Note> Notes { get; set; }

}

public class Note
{
    public int NoteId { get; set; }
    public int? LeadId { get; set; }
    public int? CreditApplicationId { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public DateTime NoteDate { get; set; }


    public string UserId { get; set; }

    [Required]
    public string Subject { get; set; }

    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
}

【问题讨论】:

  • 你能包含你的对象结构吗
  • “WHERE 子句”的日期条件部分在哪里。你的笔记表中有日期字段吗?您需要在 where 子句中添加日期条件,以便您可以将输出限制为仅在过去 2 天内输入的注释。另外,Take(10) 是否用于分页?
  • 我已经添加了上面的模型结构

标签: c# linq


【解决方案1】:

假设Note 类有类似DateCreated 的属性,你想要的线索是:

  • 两者都没有注释
  • 或者有一些笔记,但所有笔记都应该早于两天

这直接转化为以下条件:

var twoDaysAgo = DateTime.Now.AddDays(-2);

.Where(
    x =>
        x.Notes.Count == 0
        || 
        x.Notes.All(note => note.DateCreated.Date < twoDaysAgo.Date);
)

注意.Date - 这确保只比较日期。如果还应考虑时间,请删除。

此外,即使没有条件的第一部分,这也可以工作,因为All returns true for empty queryables,但这可能有点不直观。

【讨论】:

    【解决方案2】:
    vm.LeadsNoNotes = _context.Lead.Include(x => x.Notes).Where(x => x.Notes.Count == 0 && x.Notes.DateCreatd > DateTime.Now().AddDays(-2)).Take(10).ToList();
    

    我在您的 where 子句中加入了日期比较条件。我还没有测试过上面的代码,但你可以试一试。它会给你一个想法。您可以修改日期部分以获得准确的结果。

    【讨论】:

    • 我无法访问 notes.datecreated 的属性,因为它返回一个列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2014-06-27
    • 2018-12-04
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多