Created
February 9, 2015 04:31
-
-
Save cwschroeder/1931069abbd14c83023d to your computer and use it in GitHub Desktop.
MongoCsLinqpadExt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
// Write code to test your extensions here. Press F5 to compile and run. | |
var server = new MongoClient("mongodb://localhost").GetServer(); | |
var databases = server.GetDatabaseNames(); | |
var db = server.GetDatabase("DVSE"); | |
db.GenerateClasses(); | |
//var collection = db.GetCollection<DvseMeter>("DvseMeter"); | |
} | |
public static class MyExtensions | |
{ | |
public static void GenerateClasses(this MongoDatabase database) | |
{ | |
foreach (var name in database.GetCollectionNames()) | |
{ | |
if (name.StartsWith("system.")) | |
continue; | |
var c = database.GetCollection(name); | |
GenerateClass(c); | |
} | |
} | |
// Write custom extension methods here. They will be available to all queries. | |
public static void GenerateClass(this MongoCollection collection) | |
{ | |
SortByBuilder sbb = new SortByBuilder(); | |
sbb.Descending("_id"); | |
var result = collection.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(1); | |
Console.WriteLine("public class {0} {{", collection.Name); | |
var item = result.Last (); | |
foreach (var element in item.Elements) | |
{ | |
var typeName = element.Value.BsonType.ToString(); | |
switch(typeName) | |
{ | |
case "String": | |
typeName = "string"; | |
break; | |
case "Int32": | |
typeName = "int"; | |
break; | |
case "Null": | |
typeName = "string"; | |
break; | |
case "Boolean": | |
typeName = "bool"; | |
break; | |
} | |
Console.WriteLine("\tpublic {0} {1} {{ get; set; }}", typeName, element.Name); | |
} | |
Console.WriteLine("}"); | |
} | |
} | |
// You can also define non-static classes, enums, etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment