如何加入两个LINQ查询

时间:2017-05-03 07:44:59

标签: c# linq entity-framework-6

我有两个带有复合键的相关实体:

seekViewport("edge1-1")
grid.text("m", x = unit(0.5, "npc") + unit(1, "strwidth", "< 17"))
seekViewport("edge1-2")
grid.text("m", x = unit(0.5, "npc")+ unit(1, "strwidth", "> 17"))

是否有可能通过某些标准先过滤它们,然后因为大量记录而加入结果?

实际上,当我过滤EventDocuments时,我可以访问相关事件,但我也需要一次过滤Event和EventDocument。

我想这样做:

public class Event
{
    public string ID1 { get; set; }
    public int ID2 { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; } 
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
}

public class EventDocument
{

    public string ID1 { get; set; }
    public int ID2 { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

    public virtual ICollection<Event> Events { get; set; }
}

现在我需要将这些连接到查询并获得结果 - 从两个实体中过滤和连接数据

尝试这样做:

var events = ModelContext.Events.AsNoTracking().Select(x => x);
events = events.Where(x => x.EventData.StartsWith(FilterCriteria));


var eventDocuments = ModelContext.EventDocuments.AsNoTracking().Select(x => x);
eventsDocuments = eventDocuments.Where(x => x.LastName.StartsWith(FilterLastName));

1 个答案:

答案 0 :(得分:1)

您只需使用SelectMany查询这两个集。在查询语法中,这看起来像:

var eventsQry =
    from eventDocument in eventDocuments
    where eventDocument.LastName.StartsWith(FilterLastName)
    from ev in events
    where ev.EventData.StartsWith(FilterCriteria) && (ev.ID1 == eventDocument.ID1) && (ev.ID2 == eventDocument.ID2)
    select new { eventDocument, ev };

您不需要使用一个查询来过滤结果。您可以组合多个查询:

var eventsQry =
    from ev in events
    where ev.EventData.StartsWith(FilterCriteria)
    select ev

var documentsQry =
    from eventDocument in documentsQry
    where eventDocument.LastName.StartsWith(FilterLastName)
    select eventDocument;

var combinedQry =
    from eventDocument in documentsQry
    from ev in eventsQry
    where (ev.ID1 == eventDocument.ID1) && (ev.ID2 == eventDocument.ID2)
    select new { eventDocument, ev };