代码之家  ›  专栏  ›  技术社区  ›  sd-mustang

ASP。NET Web API和MongoDB Atlas-从数据库检索特定数据的方法

  •  0
  • sd-mustang  · 技术社区  · 6 年前

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

    我已经成功实现了一个Get()方法来返回“Patient”。现在,我想实现一个getMedicings()方法,只返回特定“患者”的药物。以下是我的“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; }
    }
    

    如何正确编写getMedicings()方法?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Andrei Dragotoniu    6 年前

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

    更改方法的返回类型:

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