asp.net-mvc - 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() 方法?
解决方案
您的问题是,当您的方法只返回一项时,您正在返回一个集合,因此您需要确保类型匹配。
更改方法的返回类型:
public async Task<ICollection<Medication>> GetMedications(string id)
推荐阅读
- android - 如何为不同的产品风格定义两个不同版本的字符串?
- blazor - 如何在 Blazor 中处理 dialog.onclose 事件
- mysql - 一组中第一行和第二行之间的 SQL 平均时间
- python - Python:如何在外部文件中保存和提取分数和数据并将它们分类为高分
- excel - NA() 函数返回 #### 而不是字符串 #N/A
- codenameone - 我在哪里可以获得 CN1 模拟器的 iPhone 11 皮肤?
- python - 关于使用描述符实现类型检查的困惑
- python - Python:对非常量和非增加信号进行上采样
- c++ - 为什么我不能明确地向 std::make_pair 提供元素类型?
- sql - 你能加入你使用`as`定义的变量名(在SQL中)