为简单起见,表格定义为
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,CONSTRAINT [PK_tableB] PRIMARY KEY CLUSTERED ([Key] ASC));
或者如果您首先喜欢代码
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; }}
作为我的努力
((A intersect not B) union (A intersect B))
var leftOuterJoin = tableA .GroupJoin( tableB,a => a.Key,b => b.Key,(x,y) => new { tableA = x,tableA = y }) .SelectMany( x => x.tableB.DefaultIfEmpty(),y) => new { tableA = x.tableA,tableB = y});
(A intersects B)
var innerJoin = tableA .Join( tableB,y) => x)
(A union B)
var fullOuterJoin = tableA .FullOuterJoin( tableB,y,Key) => new {x,y})解决方法 对你来说最重要的是知道如何执行INNER JOIN和OUTER JOIN.
对于INNER JOIN,您可以使用liNQ中的JOIN,如下所示:
var result = tableA .Join(tableB,left => left.ID,right => right.ForeignKeyTotableA,(left,right) => new { tableAColumns = left,tableBColumns = right });
您已在示例中显示的OUTER JOIN.
现在你需要混合你所知道的,以获得理想的结果.
例如,要执行FulL OUTER JOIN,请在liNQ中执行类似此伪代码的 *** 作:
SELECT tableA.*,tableB.* FROM tableA left OUTER JOIN tableBUNIONSELECT tableA.*,tableB.* FROM tableB left OUTER JOIN tableA
这将在liNQ中如下:
var fullOuterJoin = ( tableA .GroupJoin(tableB,right => right.ForeignKeyID,right) => new { tableA = left,tableB = right }) .SelectMany(p => p.tableB.DefaultIfEmpty(),y) => new { tableA = x.tableA,tableB = y }) ) .Union ( tableB .GroupJoin(tableA,right) => new { tableA = right,tableB = left }) .SelectMany(p => p.tableA.DefaultIfEmpty(),y) => new { tableA = y,tableB = x.tableB }) );
然后,您图像的最后一个示例是:
var fullOuterJoinOnlyWithNulls = fullOuterJoin .Where(p => p.tableA == null || p.tableB == null);
一个正确的外部联接只是一个left OUTER JOIN,您可以像这样交换结果列:
var rightOuterJoin = ( tableB .GroupJoin(tableA,y) => new { tableA = y,tableB = x.tableB }) );
像这样你可以构建所有的示例场景.只需在需要时检查表是否为null.
总结以上是内存溢出为你收集整理的c# – 如何在lambda中进行sql连接?全部内容,希望文章能够帮你解决c# – 如何在lambda中进行sql连接?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)