ASP.NET MVC4に組み込まれているRESTAPIを介してMongoDBコレクション内のすべてのドキュメントを廃止しようとしていますが、localhost:50491 / api/documentと入力するとエラーが発生します。
クラスAcord_Rest_API.Models.DocumentのIdプロパティの逆シリアル化中にエラーが発生しました:BsonTypeObjectIdから文字列を逆シリアル化できません。
私のコントローラーは次のようになります:
public class DocumentController : ApiController
{
public readonly MongoConnectionHelper<Document> docs;
public DocumentController()
{
docs = new MongoConnectionHelper<Document>();
}
public IList<Document> getAllDocs()
{
var alldocs = docs.collection.FindAll();
return alldocs.ToList();
}
}
私のMongoDBドキュメントは次のようになりますか?
ここで何が欠けていますか?
DBに接続する私のクラス:
public class MongoConnectionHelper<T> where T: class
{
public MongoCollection<T> collection { get; private set; }
public MongoConnectionHelper()
{
string connectionString = "mongodb://127.0.0.1";
var server = MongoServer.Create(connectionString);
if (server.State == MongoServerState.Disconnected)
{
server.Connect();
}
var conn = server.GetDatabase("Acord");
collection = conn.GetCollection<T>("Mappings");
}
}
ここで編集するのが私の解決策です:
MongoConnectionHelperはDBへの接続を行い、DocumentControllerにはすべてのドキュメントを取得するメソッドがあり、Documentには回答で提案した内容が含まれています。
ここで編集するのはDocumentクラスです。
[DataContract]
public class Document
{
public ObjectId _id { get; set; }
[DataMember]
public string MongoId
{
get { return _id.ToString(); }
set { _id = ObjectId.Parse(value); }
}
public IList<string> alldocs { get; set; }
}