Linq-to-Entities Left JOIN

前端 未结 7 860
终归单人心
终归单人心 2021-01-12 09:02

This is my query:

from forum in Forums
    join post in Posts on forum equals post.Forum into postGroup    

    from p in postGroup     
    where p.ParentP         


        
7条回答
  •  清歌不尽
    2021-01-12 09:10

    Here is some code to help you to work out Left Join with Link

        private class EntityRole
        {
            public int EntityId { get; set; }
            public int RoleId { get; set; }
        }
    
        private IList GetSourceEntityRole()
        {
            var list = new List() {new EntityRole(){EntityId = 123, RoleId = 1},
                                               new EntityRole(){EntityId = 123, RoleId = 2},
                                               new EntityRole(){EntityId = 123, RoleId = 3},
                                               new EntityRole(){EntityId = 123, RoleId = 4}};
    
            list.Reverse();
    
            return list;
        }
    
        private IList GetEmptyEntityRole()
        {
            var list = new List();
    
            return list;
        }
    
        public void TestToDelete()
        {
            var source = this.GetSourceEntityRole();
            var destination = this.GetEmptyEntityRole();
    
            this.TestLeftJoin(source, destination);
        }
    
        private void TestLeftJoin(IList source, IList destination)
        {
            var inserting = this.GetMissing(source, destination);
            var deleting = this.GetMissing(destination, source);
    
            this.Enumerate("Source", source);
            this.Enumerate("Destination", destination);
    
            this.Enumerate("Deleting", deleting);
            this.Enumerate("Inserting", inserting);
        }
    
        private IEnumerable GetMissing(IList sourceEntities, IList destinationEntities)
        {
            return from source in sourceEntities
                   join dest in destinationEntities on source.RoleId equals dest.RoleId into joined
                   from source2 in joined.DefaultIfEmpty()
                   where source2 == null
                   select source;
        }
    
        private void Enumerate(string source, IEnumerable roles)
        {
            foreach (var item in roles)
            {
                Console.WriteLine("{0}:{1}", source, item.RoleId);
            }
        }
    

提交回复
热议问题