Wie mache ich SQL Joins in Lambda?
Von Zeit zu Zeit stoße ich auf dieses Problem, dass ich eine Teilmenge von Lambda-Joins verwende. Angesichts der Tatsache, dass ich beliebige LINQ-Erweiterungen verwenden kann, wie soll ich vorgehen, um folgende Joins zu implementieren:
Der Einfachheit halber sind Sake-Tabellen definiert als
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)
);
oder wenn Sie Code zuerst bevorzugen
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; }
}
Als meine Anstrengung((A schneide nicht B) Vereinigung (A schneide 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})