LINQ In Line Property Update During Join

后端 未结 6 1420
难免孤独
难免孤独 2021-02-05 11:55

I have two obects, A & B for this discussion. I can join these objects (tables) via a common relationship or foreign key. I am using linq to do this join and I only want t

6条回答
  •  遥遥无期
    2021-02-05 12:22

    I am doing a left join here so I still have all the data from objectA even if the corresponding property in objectB is null. So if the corresponding property in objectB is null then you have to define what to do in objectA. I use this statement all the time for joining two sets of data. You do not need to exhaustively list all properties in objectA and how they map, you only need to list the values you want to update with objectB. Pre-existing values in objectA are safe unless a mapping to objectB is defined.

    return from objectA in GetObjectAs()
       join objectB in GetObjectBs()
       on objectA.Id equals objectB.AId into combinedObj
       from subObject in combinedObj.DefaultIfEmpty()
       // update object A with object B data before selecting it
       select ((Func)(() =>
        {
            objectA.property = ((subObject == null) ? "Object B was null" : subObject.property);
            objectA.property = ((subObject == null) ? "Object B was null" : subObject.property);
            return objectA;
        }))()
    

提交回复
热议问题