我们在C#.NET项目中对Mongo数据库进行了一点点调查,看看它是否适合我们,而且我遇到了samus对mongodb-csharp驱动程序的一个小问题,我不确定如何实现.
鉴于以下简化模型:
public class Campaign { public string Name { get; set; } public IEnumerablePlacements { get; set; } } public class Placement { public string Name { get; set; } //this should be a reference rather than included in the collection public Site Site { get; set; } } //this should be its own collection, and not embedded anywhere public class Site { public string Name { get; set; } }
我们试图弄清楚,如上面的评论所示,如何将Site保存为引用类型而不是嵌入Placement中.网站是其自己的顶级集合,可以独立于每个广告系列进行更改.
理想情况下,我想使用MongoConfigurationBuilder而不是修改我的POCO.我似乎无法找到有关如何实现这一目标的任何文档.
我希望它会像以下一样简单:
var config = new MongoConfigurationBuilder(); config.Mapping(mapping => { //maybe some more configuration here? mapping.Map(); mapping.Map (); });
但是当我使用以下代码时,它仍然嵌入了网站:
var db = mongo.GetDatabase("foo"); var campaignCollection = db.GetCollection(); var siteCollection = db.GetCollection (); var firstSite = new Site{Name = "first site"}; var secondSite = new Site{Name = "second site"}; var firstCampaign = new Campaign { Name = "first campaign", Placements = new List { new Placement{Name = "first placement", Site = firstSite}, new Placement{Name = "second placement", Site = secondSite} } }; siteCollection.Save(firstSite); siteCollection.Save(secondSite); campaignCollection.Save(firstCampaign);
这给了我们:
{ "_id" : ObjectId("4ca9f1db54730000000010cb"), "Name" : "first campaign", "Placements" : [ { "Name" : "first placement", "Site" : { "Name" : "first site" } }, { "Name" : "second placement", "Site" : { "Name" : "second site" } } ]} { "_id" : ObjectId("4ca9f1db54730000000010c9"), "Name" : "first site" } { "_id" : ObjectId("4ca9f1db54730000000010ca"), "Name" : "second site" }
而我们想要更像的东西:
{ "_id" : ObjectId("4ca9f1db54730000000010cb"), "Name" : "first campaign", "Placements" : [ { "Name" : "first placement", "Site" : ObjectId("4ca9f1db54730000000010c9") }, { "Name" : "second placement", "Site" : ObjectId("4ca9f1db54730000000010ca") } ]} { "_id" : ObjectId("4ca9f1db54730000000010c9"), "Name" : "first site" } { "_id" : ObjectId("4ca9f1db54730000000010ca"), "Name" : "second site" }
我不确定这是否是我们最终得到的确切文件,但你明白了.
我觉得好像缺少一些明显的东西,但如果没有关于驾驶员这方面的更好的文档,我就是在黑暗中拍摄.我甚至仔细查看了源代码中的测试,但无法弄明白.
有谁知道如何做到这一点?可能吗?
为此,您必须使用DBRef.
要在c#中执行此操作,您必须像这样更改广告系列类
public class Campaign { public string Name { get; set; } public ListPlacements { get; set; } }
并插入这样的参考文件
ListrefList = new List () {firstSite,secondSite }; var firstCampaign = new Campaign { Name = "first campaign", Placements = refList }; campaignCollection.Save(firstCampaign);
我没有测试过代码,但这给出了如何实现这一目的的提示.