如何在连接表上使用LINQ

本文关键字:LINQ 连接 | 更新日期: 2023-09-27 18:02:32

我试图在LINQ中复制的查询是:

SELECT count(*) FROM joinTable WHERE object1ID = input_parameter1_from_code 
AND object2ID = input_parameter2_from_code;

我可以访问一个IdentityDbContext,但它只包含对组成对象的表的引用,而不是对连接表本身的引用,所以我不知道要寻找什么来尝试获得结果。

或者,如果我只能使用这个原始查询,我想知道如何做到这一点。谢谢你。

如何在连接表上使用LINQ

我假设您已经记住了many-to-many与隐式"链接"("连接","连接")表的关系。像这样的东西(很可能你说的是UserRole,但这不是必需的):

public class One
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Two> Twos { get; set; }
}
public class Two
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<One> Ones { get; set; }
}
public class MyDbContext : DbContext
{
    public DbSet<One> Ones { get; set; }
    public DbSet<Two> Twos { get; set; }
}

虽然您不能直接访问链接表,但是您可以使用两个"主"表中的任何一个,并结合另一个的导航属性。

,

var db = new MyDbContext();

int count =
    (from one in db.Ones
     from two in one.Twos
     where one.Id == input_parameter1_from_code && two.Id == input_parameter2_from_code
     select new { one, two })
     .Count();

int count =
    (from two in db.Twos
     from one in two.Ones
     where one.Id == input_parameter1_from_code && two.Id == input_parameter2_from_code
     select new { one, two })
     .Count();

将产生类似于下面的相同SQL查询:

SELECT
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT
        COUNT(1) AS [A1]
        FROM [dbo].[TwoOne] AS [Extent1]
        WHERE (1 = [Extent1].[One_Id]) AND (2 = [Extent1].[Two_Id])
    )  AS [GroupBy1]

,你可以看到它是反对链接表的

查询语法:

var amount = (from record in DBcontext.joinTable
              where record.object1ID = input_parameter1_from_code &&
                    record.object2ID = input_parameter2_from_code
              select record).Count();

方法语法:

var amount = DBcontext.joinTable
                      .Where(record => record.object1ID = input_parameter1_from_code &&
                                       record.object2ID = input_parameter2_from_code)
                      .Count();

您可以使用Database。SqlQuery方法,它接受原始sql查询以及您需要在查询中使用的参数,使用sql parameter的优点是避免使用sql injection

试试:

var data = yourContext.Database.SqlQuery<int>(
    "SELECT count(*) FROM joinTable WHERE object1ID = @code1 AND object2ID = @code2",
    new SqlParameter("@code1", input_parameter1_from_code),
    new SqlParameter("@code2", input_parameter2_from_code)
);

让我知道如果这对你不起作用:)

您绝对可以将该查询与DbContext一起使用。看一下这里的MSDN文档:

https://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executequery (v = vs.110) . aspx

应该是这样的:

var Count = DbContext.ExecuteQuery("SELECT count(*) FROM joinTable where object1ID = input_parameter1_from_code 
AND object2ID = input_parameter2_from_code;");

这应该可以工作,即使在链接表

的情况下
dbContext.CollectionOne.where(x => x.Id ==  1).SelectMany(x => x.Collection2).where(y => y.Id == 2).Count()