c# - converting the POCO Model into MongoDB's Bson format -
here information development environment:
microsoft visual studio community 2015
.net framework 4.6
asp.net mvc assembly system.web.mvc version=5.2.3.0
mongodb.driver 2.0.1.27
mongodb 3.0.6
within c# application, have following code retrieves mongodb database reference:
public class mongodbconnectionmanager { public imongodatabase getmongodb() { var client = new mongoclient("mongodb://localhost:27017"); imongodatabase imgdb = client.getdatabase("foo"); imongocollection<bsondocument> userdetails = imgdb.getcollection<bsondocument>("users"); return imgdb; } // end of public imongodatabase getmongodb() } // end of public class mongodbconnectionmanager
here poco class represent user business entity:
using mongodb.bson.serialization.attributes; public class usermodel { public object _id { get; set; } //mongodb uses field identity. [bsonid] public int id { get; set; } [required] [bsonrepresentation(mongodb.bson.bsontype.string)] public string username { get; set; } [required] //[datatype(datatype.password)] [bsonrepresentation(mongodb.bson.bsontype.string)] public string password { get; set; } [required] // [datatype(datatype.emailaddress)] [bsonrepresentation(mongodb.bson.bsontype.string)] public string email { get; set; } [bsonrepresentation(mongodb.bson.bsontype.string)] public string phoneno { get; set; } [bsonrepresentation(mongodb.bson.bsontype.string)] public string address { get; set; } }
here dao c# class uses mongo db connection manager class:
public class dao { public int insertnewuser(usermodel um) { mongodbconnectionmanager mgodbcntmng = new mongodbconnectionmanager(); imongodatabase database = mgodbcntmng.getmongodb(); imongocollection <bsondocument> userdetails = database.getcollection<bsondocument>("users"); userdetails.insertoneasync(um); return 0; } }
the problem i'm facing following line of code in dao class:
userdetails.insertoneasync(um);
visual studio community 2015 displays following error:
cannot convert 'usermodel' mongodb.bson.bsondocument
i believe error has somehow translating usermodel poco mongodb's bson format. therefore, in usermodel poco, used use space called mongodb.bson.serialization.attributes because thought needed use mongodb annotations. however, still failed solve problem.
could please tell me how correct problem?
you should remove _id property model generated mongo , don't need add yourself. can mark properties should included in model [bsonelement] attribute except [bsonid].
also should serialize , deserialize own model not bsondocument :
mongocollection<usermodel> userdetails = database.getcollection<usermodel>("users"); userdetails.insertoneasync(um);
you creating custom class , trying fetch , insert bsondocument without conversion. if want work directly bsondocument can call this:
var umtobson = um.tobsondocument();
and insert trying to.
Comments
Post a Comment