I'm new to both C# and MongoDB. I'm trying to add a new object to a list in a MongoDB collection, here is my code:
ProjectModel:
class ProjectModel { [BsonId] public Guid Id { get; set; } public string ProjectNumber { get; set; } public string ProjectName { get; set; } public PartModel[] Parts { get; set; } } PartModel:
class PartModel { public string PartNumber { get; set; } public string PartName { get; set; } } Method Class
class MongoCRUD { private IMongoDatabase db; public MongoCRUD(string database) { var client = new MongoClient(); db = client.GetDatabase(database); } public void InsertPart<T>(string table, Guid id, PartModel newPart) { var collection = db.GetCollection<T>(table); var filter = Builders<T>.Filter.Eq("Id", id); var update = Builders<ProjectModel>.Update.Push<PartModel>(e => e.Parts, newPart); } } Main Class:
class Program { static void Main(string[] args) { MongoCRUD db = new MongoCRUD("PartsManagerDB"); PartModel newPart = new PartModel() { PartName = "Lower Bracket", PartNumber = "4000" }; db.InsertPart<PartModel>("Projects", new Guid("f3784ba4-c422-43e0-80fd-41bb87b20f10"), newPart); } } The project 93100 is already in my db, but after executing my code, no error comes up but the collection is not being updated as you can see below:
https://stackoverflow.com/questions/65534515/c-sharp-mongodb-insert-new-object-to-list January 02, 2021 at 07:08AM
没有评论:
发表评论