我有兩個表格Documents和Group如下所示。我首先使用代碼加入了創建DocumentsGroup的兩個表。
檔案表:
public class Documents
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Group> Groups { get; set;
}
組表:
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Documents> Documents { get; set; }
}
這是 DocumentsGroup 表。這是連接表,它沒有模型,而只是顯示它的外觀。
{
public int DocumentsId { get; set; }
public int GroupsId{ get; set; }
}
我正在嘗試從聯結表中獲取屬于一組的所有檔案。我有組 ID,所以我試圖獲取屬于該 ID 的所有檔案,如下所示:
int groupId = 4;
var documents = _database.Groups.Where(d => d.Id == groupId).Include(i => i.Documents).ToList();
我試過了,但沒有得到屬于該組的所有檔案。有什么做錯了嗎?
uj5u.com熱心網友回復:
使用以下查詢:
int groupId = 4;
var query =
from g in _database.Groups
from d in g.Documents
where g.Id == groupId
select d;
var documents = query.ToList();
或者通過方法鏈語法:
int groupId = 4;
var documents = _database.Groups
.Where(g => g.Id == groupId)
.SelectMany(g => g.Documents)
.ToList();
uj5u.com熱心網友回復:
嘗試通過映射表到達 Documents
int groupId = 4;
var documents = _database.DocumentsGroup
.Where(x => x.GroupId == groupId)
.Include(x => x.Documents)
.Select(x => new Documents
{
Id = x.Documents.Id,
// add all props you need
})
.ToList();
但是,如果您沒有映射表,只需創建它,或者您可以嘗試:
int groupId = 4;
var documents = _database.Groups
.Include(x => x.Documents)
.Where(x => x.Id == groupId )
.ToList();
uj5u.com熱心網友回復:
您撰寫的查詢將回傳一組結果集,而不是檔案。如果“Group”表的“Id”列是唯一的,你應該這樣寫:
var group = dbContext.Groups.Include(g => g.Documents).FirstOrDefault(g => g.Id == 4); //Given group id is 4
if (group != null) {
var documents = group.Documents.ToList(); // Here you should get the desired Documents, given that the the tables are correctly configured
}
如果這對您沒有幫助,請提供更多詳細資訊。如果這有幫助,請投票:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453504.html
標籤:C# asp.net-mvc 林克
上一篇:創建具有隨機不同數字的彩票
