[英]How to use LINQ on a join table?
我試圖在LINQ中復制的查詢是:
SELECT count(*) FROM joinTable WHERE object1ID = input_parameter1_from_code
AND object2ID = input_parameter2_from_code;
我可以訪問IdentityDbContext,但是它僅包含對組成對象表的引用,而不是對聯接表本身的引用,因此我不知道要查找什么才能嘗試獲得結果。
另外,如果我只能使用這個原始查詢,我也想知道如何做。 謝謝。
我假設您已經考慮many-to-many
具有隱式“ link”(“ join”,“ junction”)表many-to-many
關系。 這樣的事情(很可能您是在講User
和Role
,但這不是必需的):
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();
在Method語法中:
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 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/zh-CN/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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.