我有两个表:tbA
和tbB
。在它们之间我有一个n到n的关系,所以在数据库中生成了一个表tbAB
。我首先使用实体框架数据库,然后当我映射这些表时,它不会为tbAB
生成特定实体。因此,如果我无法直接调用tbAB
,我就无法看到如何创建与这两个表相关的查询。
我想在SQL中做的事情如下:
SELECT *
FROM tbA
INNER JOIN tbAB
ON tbAB.idA = tbA.idA
INNER JOIN tbB
ON tbB.idB = tbAB.idB
这就是我尝试用Linq做的事情:
var table = (from l in db.tbA
join k in db.tbB on l.? equals k.?
where ?.IDCONCESSAO == objectTbB.IDCONCESSAO
select l).ToList();
问题是如何在Linq表达式中执行此操作?
提前致谢。
答案 0 :(得分:2)
按照@Michal提出的模型,您可以这样做:
var query= from a in db.TableAs
from b in a.TableBs
where b.Id==10
select new{A_Id=a.Id,a.Name, B_Id=b.Id,b.Price,...};
在select
中,您可以从两个实体中选择所需的属性(我还从Name
选择TableA
,从Price
选择TableB
帮助你更好地理解这个例子。从关系的每个方向,你都不会与junction table进行交互,你只需要跟随每个方向的关系,就好像它是一对多关系一样。我在上面显示的查询将在sql查询中进行转换,其中表之间的连接将以这种方式进行:
{SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Join1].[Id] AS [Id1],
[Join1].[Price] AS [Price]
FROM [dbo].[TableAs] AS [Extent1]
INNER JOIN (SELECT [Extent2].[TableA_Id] AS [TableA_Id], [Extent3].[Id] AS [Id], [Extent3].[Price] AS [Price]
FROM [dbo].[TableBTableAs] AS [Extent2]
INNER JOIN [dbo].[TableBs] AS [Extent3] ON [Extent3].[Id] = [Extent2].[TableB_Id] ) AS [Join1] ON [Extent1].[Id] = [Join1].[TableA_Id]
WHERE 10 = [Join1].[Id]}
答案 1 :(得分:1)
public void Test()
{
var db = new DbContext();
// This will automatically do you inner join for you.
db.TableAs.Include(a => a.TableBs);
}
上下文:
public class DbContext
{
public IDbSet<TableA> TableAs { get; set; }
public IDbSet<TableB> TableBs { get; set; }
}
型号:
public class TableA
{
public int Id { get; set; }
public virtual List<TableB> TableBs { get; set; }
}
public class TableB
{
public int Id { get; set; }
public virtual List<TableA> TableAs { get; set; }
}
答案 2 :(得分:0)
var table = from a in db.tbA
join ab in db.tbAB on a.idA equals ab.idA
join b in db.tbB on ab.idB equals b.idB
where a.Anything = 10
select a;
var results = table.ToList();