实体框架LINQ获取另一个集合中的所有项目

问题描述:

从DBContext中获取所有与RelationsCollection中的记录重叠的NWatchRelation记录. 相同的Id,RelatedNodeId和RelationType(枚举:int)应视为匹配项.

Get all the NWatchRelation records from the DBContext that overlap those in the relationsCollection. The same Id, RelatedNodeId, and RelationType (enum: int) should be what's considered a match.

public class NWatchRelation : INWatchRelation
{
    public int Id { get; set; }
    public int NodeId { get; set; }
    public NWatchNode Node { get; set; }
    public int RelatedNodeId { get; set; }

    public NWatchNode RelatedNode { get; set; }
    public NWatch.NWatchRelationType RelationType { get; set; }
}

INWatchRelation[] relationsCollection = GetRelations();

您可以在LINQ to Entities中完全做到这一点的唯一方法是使用UNION ALL查询. microsoft.com/en-us/library/bb351755(v=vs.110).aspx"rel =" nofollow> Queryable.Concat 像这样:

The only way you can do that fully in LINQ to Entities is to manually compose UNION ALL query by using Queryable.Concat like this:

IQueryable<NWatchRelation> query = null;
foreach (var relation in relationsCollection)
{
    var m = relation;
    var subQuery = db.NWatchRelations
        .Where(r => r.Id == m.Id
            && r.RelatedNodeId == m.RelatedNodeId
            && r.RelationType == m.RelationType);
    query = query == null ? subQuery : query.Concat(subQuery);
}

但是请注意,这是一种有限的方法,如果relationsCollection很大,将无法使用.

But please note that it's a limited approach and will not work if the relationsCollection is big.