public List<ClassParticipantViewModel> GetClassParticipants(string studentId)
{
List<ClassParticipantViewModel> list = new List<ClassParticipantViewModel>();
var results = (from cp in _DbContext.ClassParticipants
join c in _DbContext.Classes
on cp.ClassId equals c.ClassId
where cp.StudentId.Equals(studentId)
select new ClassParticipantViewModel
{
//ClassParticipant
ClassParticipantId = cp.ClassParticipantId,
StudentId = cp.StudentId,
ClassParticipantCreatedOn = cp.CreatedOn,
//Class
ClassId = c.ClassId,
ClassCode = c.ClassCode,
Section = c.Section,
CourseCode = c.CourseCode,
Description = c.Description,
Units = c.Units,
CreatedBy = c.CreatedBy,
ClassCreatedOn = c.CreatedOn,
})
.ToList();
list = list.Concat(results).ToList();
return list.ToList();
}
加入錯誤:

楷模:

視圖模型:

我正在使用 .NET Core 3.0 開發 Web API,然后出現錯誤,指出對“加入”的呼叫不明確,此代碼在我的其他專案中有效。我很困惑,如果出了什么問題,我的模型的命名約定是否有影響?
uj5u.com熱心網友回復:
EF 中導航道具的快速介紹:
如果您的課程看起來像:
class Class {
ICollection<ClassParticipant> ClassParticipants {get; set;}
...
}
class ClassParticipant {
Class Class{get;set;}
Participant Participant{get;set;}
...
}
class Participant{
ICollection<ClassParticipant> ParticipantClasses {get; set;}
...
}
EF 將能夠計算出這是類之間典型的 1:M:1 關系:classparticipants:participants - 許多類有很多參與者,中間的表格將其分解。
完成該屬性映射后,您可以撰寫如下查詢:
_DbContext.ClassParticipants.Select(cp =>
new ClassParticipantViewModel
{
//ClassParticipant
ClassParticipantId = cp.ClassParticipantId,
StudentId = cp.StudentId,
ClassParticipantCreatedOn = cp.CreatedOn,
//Class
ClassId = cp.Class.ClassId,
ClassCode = cp.Class.ClassCode,
Section = cp.Class.Section,
CourseCode = cp.Class.CourseCode,
Description = cp.Class.Description,
Units = cp.Class.Units,
CreatedBy = cp.Class.CreatedBy,
ClassCreatedOn = cp.Class.CreatedOn,
}
).ToList();
EF 將看到您在選擇 ( cp.Class.ClassId) 中導航,并且知道它必須加入類才能獲取您想要的資料。您還可以在Where子句中以類似方式進行直接導航參考以加載相關資料,或者,如果您知道不會在Selector 中參考相關資料Where,但您希望加載資料以便您可以以后在C#中參考,可以使用Include:
_DbContext.ClassParticipants.Include(cp => cp.Class).ToList();
腳注,您可能想要例如ICollection<ClassParticipant> ClassParticipants {get; set;} = new HashSet<ClassParticipant>();因為它使創建新物體更容易,而不必記住先制作集合:
var c = new Class(...);
var p = new Participant(...);
//can do this without having to remember to make a new collection
c.ClassParticipants.Add(new ClassParticipant { Class = c, Participant = p });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/369367.html
上一篇:EF添加新記錄而不是更新記錄
