首页 > 解决方案 > ASP.NET Web API 和 MongoDB Atlas - 从数据库中检索特定数据的方法

问题描述

我在 Visual Studio Community Edition 2017 中创建了一个 ASP.NET Web API 项目(使用 .NET Framework 4.6.1),该项目通过 MongoDB .NET 驱动程序利用了 MongoDb Atlas。该项目存储具有几个不同属性的“患者”。

我已经成功实现了一个 Get() 方法来返回一个“Patient”。我现在想实现一个 GetMedications() 方法以仅返回特定“患者”的药物。以下是我的“PatientsController”文件中的相关方法:

public async Task<Patient> Get(string id)
{
    try
    {
        ObjectId internalId = GetInternalId(id);
        return await _patients.Find(p => p.Id == id || p.InternalId == internalId).FirstOrDefaultAsync();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

[Route("api/patients/{id}/medications")]
public async Task<Medication> GetMedications(string id)
{
    try
    {
        ObjectId internalId = GetInternalId(id);
        var patient = await _patients.Find(p => p.Id == id || p.InternalId == internalId).FirstOrDefaultAsync();
        return patient.Medications;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private ObjectId GetInternalId(string id)
{
    ObjectId internalId;
    if (!ObjectId.TryParse(id, out internalId))
        internalId = ObjectId.Empty;

    return internalId;
}

Visual Studio 显示此错误return patient.Medications

Cannot implicitly convert type 'Systems.Collections.Generic.ICollection<WebAPIDemo.Models.Medication>' to 'WebAPIDemo.Models.Medication'

这是我的患者课程(和其他适用课程):

public class Patient
{
    [BsonId]
    public ObjectId InternalId { get; set; }

    public string Id { get; set; }
    public string Name { get; set; }
    public ICollection<Ailment> Ailments { get; set; }
    public ICollection<Medication> Medications { get; set; }
}

public class Medication
{
    public string Name { get; set; }
    public int Doses { get; set; }
}

public class Ailment
{
    public string Name { get; set; }
}

我怎样才能正确编写 GetMedications() 方法?

标签: asp.net-mvcmongodbasp.net-web-apigetmongodb-.net-driver

解决方案


您的问题是,当您的方法只返回一项时,您正在返回一个集合,因此您需要确保类型匹配。

更改方法的返回类型:

public async Task<ICollection<Medication>> GetMedications(string id)

推荐阅读