MongoDBで簡単なWebAPIを構築しようとしましたが、_idの値に基づいてPatientドキュメントを返します。MongoDB .FindSync()の結果をシリアル化できません。
患者の定義、Patient.cs
namespace PatientData.Models
{
public class Patient
{
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public ICollection<Medication> Medications { get; set; }
}
public class Medication
{
public string Name { get; set; }
public int Doses { get; set; }
}
}
データベースのMongoDBアクセス、PatientDB.cs:
namespace PatientData.Models
{
public static class PatientDB
{
static MongoClient client = new MongoClient("mongodb://localhost");
static IMongoDatabase db = client.GetDatabase("Patients");
public static IMongoCollection<Patient> Open()
{
return db.GetCollection<Patient>("Patients");
}
public static IQueryable<Patient> query()
{
return db.GetCollection<Patient>("Patients").AsQueryable<Patient>(); // .AsQueryable() is still availabe in driver version 2.# as an extension for collection. so .Any() is still available as well.
}
}
}
API コントローラ:
[OK]をコンパイルnamespace PatientData.Controllers
{
public class PatientsController : ApiController
{
IMongoCollection<Patient> _patients;
public PatientsController()
{
_patients = PatientDB.Open();
}
public IEnumerable<Patient> Get()
{
return _patients.Find<Patient>(_=>true).ToList();
}
public HttpResponseMessage Get(string id)
{
var theFilter = Builders<Patient>.Filter.Eq("Id", id);
var thePatient = _patients.FindSync<Patient>(theFilter);
//return (Patient)thePatient;
return Request.CreateResponse(thePatient);
}
}
}
、実行時例外を持って、例えば、URL
http://localhost:49270/api/Patients/5768a6f48200fa07289c93e8 タイプ 「MongoDB.Driver.Core.Operations.AsyncCursor`1 [PatientData.Models .Patient] ' はシリアル化できません。 DataContractAttribute属性でそれをマークし、すべてのメンバを にマークすることをDataMemberAttribute属性でシリアル化する必要があることを考慮してください。タイプが のコレクションの場合は、 CollectionDataContractAttributeでマークすることを検討してください。他のサポートされている種類については、Microsoft .NET Framework のドキュメントを参照してください。
返される型ではない "HttpResponseMessage" "患者" であり、実行時例外がより興味深いものです
return (Patient)thePatient;
を使用する場合:
「System.InvalidCastExceptionの オブジェクトをキャストすることができません型 'MongoDB.Driver.Core.Operations.AsyncCursor`1 [PatientData.Models.Patient]'を入力して 'PatientData.Models.Patient'と入力します。
カーソルがPatientData.Models.Patientとして入力されている場合は、なぜその型にすることはできませんか?
これはScott AllenのASP.NET MVC 5 Fundamentals、WebAPI 2、Query by IDに基づいています。彼は
鉱山がある1.xのドライバーを使用しています:
- モンゴサーバ3.2、64ビット
これは素晴らしいですようにそれを作るために
を追加します。私がした最も簡単な方法は 'var thePatient = _patients.FindSync(theFilter);'です。私はMongoのDocがこれをもっと詳しく説明してくれることを願っています。 –