¿Cómo hacer uniones sql en lambda?
De vez en cuando, me encuentro con este problema que utilizo un subconjunto de combinaciones lambda. Dado que puedo usar cualquier extensión de LINQ, ¿cómo debo implementar las siguientes combinaciones?
Por simplicidad, las tablas de sake se definen como
CREATE TABLE [dbo].[TableA] (
[Key] INT IDENTITY (1, 1) NOT NULL,
[Value] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_TableA] PRIMARY KEY CLUSTERED ([Key] ASC)
);
CREATE TABLE [dbo].[TableB] (
[Key] INT IDENTITY (1, 1) NOT NULL,
[Value] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_TableB] PRIMARY KEY CLUSTERED ([Key] ASC)
);
o si prefieres el código primero
public class TableContext : DbContext
{
public DbSet<B> TableB { get; set; }
public DbSet<A> TableA { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TableB>().Property(o => o.Key).UseSqlServerIdentityColumn();
modelBuilder.Entity<TableA>().Property(o => o.Key).UseSqlServerIdentityColumn();
}
}
public class B : IKeyValue
{
public int Key { get; set; }
public string Value { get; set; }
}
public class A : IKeyValue
{
public int Key { get; set; }
public string Value { get; set; }
}
public interface IKeyValue
{
int Key { get; set; }
string Value { get; set; }
}
Como mi esfuerzo((Una intersección no B) unión (Una intersección B))
var leftOuterJoin = TableA
.GroupJoin(
TableB,
a => a.Key,
b => b.Key,
(x, y) => new { TableA = x, TableA = y })
.SelectMany(
x => x.TableB.DefaultIfEmpty(),
(x, y) => new { TableA = x.TableA, TableB = y});
var innerJoin = TableA
.Join(
TableB,
a => a.Key,
b => b.Key,
(x, y) => x)
var fullOuterJoin = TableA
.FullOuterJoin(
TableB,
a => a.Key,
b => b.Key,
(x, y, Key) => new {x, y})