【发布时间】:2021-03-24 05:12:20
【问题描述】:
EF Core 和 .NET 5.x
我的问题是用 linq / query 定义如何得到这个结果。总共需要连接 7 个表。为简单起见,简化了 7 个表格。底部的 sql 是我想要得到到目前为止行代码所在的结果。
public class SP
{
int spKey { get; set; }
string spValue { get; set; }
}
public class SV
{
int svKey { get; set; }
string svValue { get; set; }
}
public class IR
{
int irKey { get; set; }
string irValue { get; set; }
}
public class UR
{
int urKey { get; set; }
string urValue { get; set; }
}
public class BE
{
int beKey { get; set; }
string beValue { get; set; }
int irKey { get; set; }
int urKey { get; set; }
[ForeignKey("irKey")]
public IR { get; set; }
[ForeignKey("urKey")]
public UR { get; set; }
}
public class SO
{
int soKey { get; set; }
int beKey { get; set; }
int spKey { get; set; }
int svKey { get; set; }
[ForeignKey("beKey")]
public BE { get; set; }
[ForeignKey("spKey")]
public SP { get; set; }
[ForeignKey("svKey")]
public SV { get; set; }
}
public class SD
{
int soKey { get; set; }
[ForeignKey("soKey")]
public SO { get; set; }
}
以下 SQL 是我想要的结果:
select *
from SD t_sd
left outer join SO t_so on t_so.soKey = t_sd.soKey
left outer join BE t_be on t_be.beKey = t_so.beKey
left outer join IR t_ir on t_ir.irKey = t_be.irKey
left outer join UR t_ur on t_ur.urKey = t_be.urKey
left outer join SP t_sp on t_sp.spKey = t_so.spKey
left outer join SV t_sv on t_sv.svKey = t_so.svKey
where t_so.beKey = 4711 and t_sp.spValue = 'test'
使用 EF Core 和 ASP.NET Core 5。
我被困在 LINQ 中使用 .Include / .ThenInclude
public SalgDetail GetBestilling(long bestilNr)
{
using (var _db = new DbContext(conString))
{
try
{
var result = _db.SD
.Include(sd => sd.SO)
.ThenInclude(so => so.BE)
.ThenInclude(b => b.IR)
.Include(sd => sd.SO)
.ThenInclude(so => so.BE)
.ThenInclude(b => b.UR)
.Include(sd => sd.SO)
.ThenInclude(so => so.SP)
.Include(sd => sd.SO)
.ThenInclude(so => so.SV);
// where do I put my 'where' clauses
return result;
}
catch
{
return null;
}
}
}
【问题讨论】:
-
最终结果应该是什么?
-
你应该把
Where放在Includes和ThenIncludes之后,通过sd引用字段。
标签: linq entity-framework-core