Csharp/C#教程:Mongodb公约包分享


Mongodb公约包

如何在c#中使用mongodb ConventionPack我有以下代码:

MongoDatabase Repository = Server.GetDatabase(RepoName); this.Collection = Repository.GetCollection(CollectionName); var myConventions = new ConventionPack(); myConventions.Add(new CamelCaseElementNameConvention()); 

约定包是否自动附加到this.Collection? 当我加载一个新对象时,它会自动保持这种情况吗? 我是否必须在类声明中添加标签(如数据合同)?

您需要在ConventionRegistry注册该包:

 var pack = new ConventionPack(); pack.Add(new CamelCaseElementNameConvention()); ConventionRegistry.Register("camel case", pack, t => t.FullName.StartsWith("Your.Name.Space.")); 

如果要全局应用它,可以用t => true类的简单替换最后一个参数。

序列化和反序列化的工作示例代码(驱动程序1.8.20,mongodb 2.5.0):

上述就是C#学习教程:Mongodb公约包分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 using System; using System.Linq; using MongoDB.Bson; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; namespace playground { class Simple { public ObjectId Id { get; set; } public String Name { get; set; } public int Counter { get; set; } } class Program { static void Main(string[] args) { MongoClient client = new MongoClient("mongodb://localhost/test"); var db = client.GetServer().GetDatabase("test"); var collection = db.GetCollection("Simple"); var pack = new ConventionPack(); pack.Add(new CamelCaseElementNameConvention()); ConventionRegistry.Register("camel case", pack, t => true); collection.Insert(new Simple { Counter = 1234, Name = "John" }); var all = collection.FindAll().ToList(); Console.WriteLine("Name: " + all[0].Name); } } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/960115.html

(0)
上一篇 2021年11月24日
下一篇 2021年11月24日

精彩推荐