EF和Linq除外

时间:2014-09-12 18:23:34

标签: c# linq entity-framework

鉴于这两个EF模型 - 我如何使用linq从InteractionSegmentDetail中选择Custom_SegmentsParsed中不存在的所有记录?使用InteractionIDKey字段作为比较器。

 public partial class Custom_SegmentsParsed
    {
        public string InteractionIDKey { get; set; }
        public string SegmentNum { get; set; }
        public System.DateTime ServerTs { get; set; }
        public System.DateTime CUTC { get; set; }
        public Nullable<int> Duration { get; set; }
        public string LocalParty { get; set; }
        public string Queue { get; set; }
        public string EndCode { get; set; }
        public string Details { get; set; }
}
  public partial class InteractionSegmentDetail
    {
        public string InteractionIDKey { get; set; }
        public short SiteID { get; set; }
        public byte SeqNo { get; set; }
        public System.DateTime StartDateTimeUTC { get; set; }
        public int StartDTOffset { get; set; }
        public string ConversationID { get; set; }
        public string SegmentLog { get; set; }
}

4 个答案:

答案 0 :(得分:2)

dbContext.InteractionSegmentDetail
         .Where(isd => !dbContext.Custom_SegmentsParsed
                                 .Select(x => x.InteractionIDKey)
                                 .Contains(isd.InteractionIDKey));

答案 1 :(得分:1)

我会使用WhereAny

isdList.Where(isd => !cspList
                     .Any(csp => isd.InteractionIDKey == csp.InteractionIDKey));

答案 2 :(得分:0)

这是一个使用有效的查询语法执行左连接的选项:

var results = 
    (from isd in db.InteractionSegmentDetails
     join csp in db.Custom_SegmentsParsed on isd.InteractionIDKey equals csp.InteractionIDKey into possibleCSPs
     from csp in possibleCSPs.DefaultIfEmpty()
     where csp.InteractionIDKey == null //ensure no CSP match was found
     select isd).Distinct().ToArray(); //don't include duplicates (just in case)

答案 3 :(得分:-1)

我会在这里使用三个查询来组合它们,在这种情况下会破坏性能。

List<string> customKeys = dbContext.Custom_SegmentsParseds.Select(s => s.InteractionIDKey).ToList();
List<string> interactionKeys = dbContext.InteractionSegmentDetails.Select(s => s.InteractionIDKey).ToList();
IEnumerable<string> overLap = interactionKeys.Except(customKeys);
List<InteractionSegmentDetail> detailList = dbContext.InteractionSegmentDetails.Where(seg => overLap.Contains(seg.InteractionIDKey)).ToList();