linq 在返回客户端之前从获取相关对象的详细信息

9rygscc1  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(120)

I am saving an object in my database, it stores the ID which relates to an object stored in another table. When I retrieve this from the database, I want to return the details of this class to the client along with the name of the related object. ie,
AntifungalAgent

ID: 1
Name: "Drug1"

InteractingDrug

ID: 1
Name: "Drug2"

Interaction

ID: 1
AntifungalID: 1
InteractingDrugID: 1

When I retrieve the data for the Interaction from my controller, the ID is the ID of the interactingDrug so it returns all interactions with that interacting drug.

[HttpGet("{id}")]
public async Task<ActionResult<List<DrugInteractions>>> getInteraction(int id)
{
    return await _context.DrugInteractions
                         .Include(di => di.InteractingDrug)
                         .Include(di => di.AntifungalAgent)
                         .Where(di => di.InteractingDrug.ID == id)
                         .ToListAsync();
}

Currently, I get a list of all the interactions as expected. But I only get a number for the antifungalAgentID and the InteractingDrugID .
I want to also get the name of these 2 drugs.
I have created a DrugInteractionDto class.

public class DrugInteractionDTO
{
    public string Antifungal { get; set; }
    public string InteractingDrug { get; set; }
    public string BasicDetailedInformation { get; set; }
    public string ProDetailedInformation { get; set; }
    public Severity Severity { get; set; }
    public int ID { get; set; }
}

But I am stuck on adding the names of the antifungalAgent and interactingDrug to this DTO, so that I can return this to the client and use the names in the UI.

kr98yfug

kr98yfug1#

根据您提供的数据,DrugInteractionAntifungalAgentInteractingDrug表之间的关联表。
抗真菌剂(1..m)--〉药物相互作用(m..1)〈--相互作用药物
生成的DrugInteraction实体类应如下所示:

public class DrugInteraction
{
    public int ID { get; set; }

    public int AntifungalAgentID { get; set; }

    public int InteractingDrugID { get; set; }

    public virtual AntifungalAgent AntifungalAgent { get; set; }

    public virtual InteractingDrug InteractingDrug { get; set; }
}

您需要.Select()将每个对象从DrugInteractions转换为DrugInteractionDTO类型。

public async Task<ActionResult<List<DrugInteractionDTO>>> getInteraction(int id)
{
    return await _context.DrugInteractions
            .Include(di => di.InteractingDrug)
            .Include(di => di.AntifungalAgent)
            .Where(di => di.InteractingDrug.ID == id)
            .Select(x => new DrugInteractionDTO
            {
                Antifungal = x.AntifungalAgent.Name,
                InteractingDrug = x.InteractingDrug.Name,
                ID = x.ID,
                // Following properties
            })
            .ToListAsync();
}

相关问题