简体   繁体   English

在子表上选择查询

[英]Select query on sub table

Im writing a basic CRM to capture leads. 我正在编写基本的CRM来捕获潜在客户。

You are able to add notes to leads. 您可以向销售线索添加注释。

I want to return a list of leads that have no notes within the last two days. 我想返回最近两天内没有备注的潜在客户列表。

I cant work out the linq query to enable this. 我无法解决linq查询以启用此功能。

So far i have the following which will return all the leads without a note. 到目前为止,我有以下内容将不带注释地返回所有线索。

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

below is my model structure 下面是我的模型结构

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; }
}

Assuming Note class has something like DateCreated property, you want leads that: 假设Note类具有类似DateCreated属性的内容,则您需要以下线索:

  • Either have no notes at all 根本没有音符
  • Or have some notes, but then all notes should be older then two days 或有一些笔记,但所有笔记都应早于两天

That directly translates into the following condition: 这直接转化为以下情况:

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

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

Notice .Date - this makes sure only dates are compared. 注意.Date确保只比较日期。 Remove if time should also be taken into account. 如果还应该考虑时间,请删除。

Also, that will work even without first part of the condition, because All returns true for empty queryables , but that might be a bit not intuitive. 而且,即使没有条件的第一部分,该方法也可以工作,因为对于空的queryablesAll返回true ,但这可能有点不直观。

vm.LeadsNoNotes = _context.Lead.Include(x => x.Notes).Where(x => x.Notes.Count == 0 && x.Notes.DateCreatd > DateTime.Now().AddDays(-2)).Take(10).ToList();

I have included a date comparison condition to your where clause. 我在您的where子句中包含了一个日期比较条件。 I haven't tested the above code but you can give it a try. 我尚未测试以上代码,但您可以尝试一下。 It will give you an idea. 它会给你一个想法。 You can modify the date part to get the exact result. 您可以修改日期部分以获得准确的结果。

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

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