[英]Add a list of objects to DTO create in entity framework c#
我的 c# controller 中有以下代碼,
[HttpGet("antifungal/{name}")]
public List<DrugInteractionDTO> test(string name)
{
var DI = (from D1 in _context.DrugInteractions
join D2 in _context.DrugInteractionReferences
on D1.ID equals D2.DrugInteractionId into joined
from D3 in joined.DefaultIfEmpty()
where D1.AntifungalAgent.Name.ToLower().Contains(name.ToLower())
select new DrugInteractionDTO
{
Severity = D1.Severity,
SeverityAsString = D1.Severity.ToString(),
ProDetailedInformation = D1.ProDetailedInformation,
BasicDetailedInformation = D1.BasicDetailedInformation,
Antifungal = D1.AntifungalAgent.Name,
InteractingDrug = D1.InteractingDrug.GenericName,
ID = D1.ID,
Count = 2
//DrugInteractionReferences
}).ToList();
return DI.OrderBy(x => x.InteractingDrug).ToList();
}
我的DrugInteractionDTO
model 有一個我想添加到的字段List<DrugInteractionReferences>
。
我的兩個表是interactions
和references
每個交互可以有很多引用。
我習慣於使用 Java (Spring),我不知道如何返回屬於 DTO 中每個交互的引用。 我正在幫助的當前應用程序非常舊並且存在很多問題。
是否可以將引用列表添加到在此代碼中創建的每個 interactionDTO?
它被稱為 Eager Loading 查詢,詳細實體應該不是通過join
而是通過子查詢表達式來檢索:
var DI = (from D1 in _context.DrugInteractions
where D1.AntifungalAgent.Name.ToLower().Contains(name.ToLower())
select new DrugInteractionDTO
{
Severity = D1.Severity,
SeverityAsString = D1.Severity.ToString(),
ProDetailedInformation = D1.ProDetailedInformation,
BasicDetailedInformation = D1.BasicDetailedInformation,
Antifungal = D1.AntifungalAgent.Name,
InteractingDrug = D1.InteractingDrug.GenericName,
ID = D1.ID,
Count = 2,
DrugInteractionReferences = _context.DrugInteractionReferences
.Where(D2 => D2.DrugInteractionId == D1.ID)
.ToList()
}).ToList();
如果遇到性能問題,請在最后一個 .ToList( .AsSplitQuery()
.ToList()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.