Reputation: 31
Hi I'm really struggling with classes and mapping a MongoDB document, I will admit I am struggling to come to understand the whole OOP thing and my coding so far is limited to just functional coding at the moment. My document has many fields but I am only interested in a few of them for the time being. I wrote my program in Python without classes but I want to recreate it in C#.
My Python code that returns the two fields.
stock_details = collection.find_one({'Stock Number' : stock_number})
#print(stock_details.keys())
val1 = stock_details['Stock Number']
val2 = stock_details['Qty In Stock']
return val1, val2,
My C# code that I'm struggling with
public static StockItem GetStockItem(string StockNumber)
{
var client = new MongoClient()
var db = client.GetDatabase("storesdb");
var collection = db.GetCollection<BsonDocument>("storeslist");
var filter = Builders<StockItem>.Filter.Eq("Stock Number", StockNumber);
var findfilter = collection.Find(filter).FirstOrDefault();
var returnValue = findfilter;
return returnValue;
}
[BsonIgnoreExtraElements]
public class StockItem
{
[BsonElement("Stock Number")]
public string stockNumber { get; set; }
[BsonElement("Qty In Stock")]
public int qtyInStock { get; set; }
}
I can successfully get a Bson document but when I try using a class, I am unable to map it to a variable/object, trying the above code gives me the following error.
Severity Code Description Project File Line Suppression State
Error CS1503 Argument 2: cannot convert from 'MongoDB.Driver.FilterDefinition<Program.StockItem>' to 'System.Linq.Expressions.Expression<System.Func<MongoDB.Bson.BsonDocument, bool>>' Storesincsharp C:\Users\zaks\source\repos\Storesincsharp\Storesincsharp\Program.cs 46 Active
Changing the document filter to Bson works okay, but trying to return it as a class object gives me this error instead.
Severity Code Description Project File Line Suppression State
Error CS0029 Cannot implicitly convert type 'MongoDB.Bson.BsonDocument' to 'Program.StockItem' Storesincsharp C:\Users\zaks\source\repos\Storesincsharp\Storesincsharp\Program.cs 48 Active
Could some one point me in the right direction?
Upvotes: 2
Views: 1843
Reputation: 613
You will want to use a typed collection. In addition, to avoid typo's you can also specify your filter names via linq rather than with string names. It also helps when you refactor your classes. Example:
public static StockItem GetStockItem(string StockNumber)
{
var client = new MongoClient();
var db = client.GetDatabase("storesdb");
var collection = db.GetCollection<StockItem>("storeslist"); // Typed collection.
var filter = Builders<StockItem>.Filter.Eq(x=> x.stockNumber, StockNumber); // Referenced property name.
StockItem returnValue = collection.Find(filter).FirstOrDefault();
return returnValue;
}
Upvotes: 2