Reputation: 1
for my final project, I'm doing a simple Manager app for Car repairment Garages, for DB I'm using MongoDB and I saw a great tutorial by Tim corny, but I don't know how to generate an Unice Id for each object.
this is my class Actions for each object in the Database
public class MongoActions
{
private static Random random;
public static void UpsertRecord<T>(int id, string table, T record)
{
var collection = Mongo.db.GetCollection<T>(table);
var result = collection.ReplaceOne(
new BsonDocument("_id", id),
record,
new UpdateOptions { IsUpsert = true }
);
}
public static int RandomId<T>(string table)
{
**//how to find a nice Id that is not repeated**
}
public static void InsertRecord<T>(string table, T record)
{
var collection = Mongo.db.GetCollection<T>(table);
collection.InsertOne(record);
}
public static T FindRecord<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).First();
}
public static List<T> FillterRecords<T>(string table, string field, string value)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq(field, value);
return collection.Find(fillter).ToList();
}
public static List<T> LoadRecords<T>(string table)
{
var collection = Mongo.db.GetCollection<T>(table);
return collection.Find(new BsonDocument()).ToList();
}
public static void DeleteRecord<T>(string table,int id)
{
var collection = Mongo.db.GetCollection<T>(table);
var fillter = Builders<T>.Filter.Eq("_id", id);
collection.DeleteOne(fillter);
}
}
and this is the connection class
public static class Mongo
{
public static string database = "Garage";
public static MongoClient client=new MongoClient();
public static IMongoDatabase db = client.GetDatabase(database);
}
I will be glad if someone help me
Upvotes: 0
Views: 456
Reputation: 14436
Change your Id to be an ObjectId
and don't set it before an insert, this way the database engine will set it on your behave and set it on your object:
Checkout the following code:
class Order
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Order>("orders");
// Leave the Id on Order as `null`
var myOrder = new Order {Name = "My Order"};
// Once we insert the Order the Id will be set.
await collection.InsertOneAsync(myOrder);
Console.WriteLine($"Order Id: {myOrder.Id}"); // Order Id: 5edbb15c75e67361d07362c2
Console.WriteLine($"Order Id: {myOrder.Name}"); // Order Id: My Order
Upvotes: 1