Home > OS >  Select all records in table B with same PK and different property values as in table A
Select all records in table B with same PK and different property values as in table A

Time:02-02

I have two tables TA and TB. Both use the same PK (TB is a shadow table of TA). I need to identify all records from TA that are also in TB, but have one or more property values changed.

Sample code:

public class MyData 
{
    public Guid PK { get; set; } = Guid.Empty;
    public int Value1 { get; set; } = 0;
    public int Value2 { get; set; } = 0;
}

What I need is something like find all records R from TA in TB where R(TA).PK == R(TB).PK && (R(TA).Value1 != R(TB).Value1 || R(TA).Value1 != R(TB).Value1)

However, I have no bloody clue how to write that down, neither as sql nor as Linq statement. I tried a lot of variants, but none was syntactically correct.

CodePudding user response:

var result = ctx.TA.Where(a => ctx.TB.Any(b => a.PK == b.PK && 
  (a.Value1 != b.Value1 || a.Value2 != b.Value2)));

CodePudding user response:

Try the following query:

var query =
    from ta in context.TableA
    join tb in context.TableB on ta.PK equals tb.PK
    where ta.Value1 != tb.Value1 || ta.Value2 != tb.Value2
    select ta;
  • Related