gpt4 book ai didi

c# - 在 C# 中建模 mongodb 子集合

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:04 25 4
gpt4 key购买 nike

我正在尝试通过 C# 驱动程序为子集合建模,但我发现这样做很难;你能帮我做一下吗?或者请给我一些完整的例子吗?

我正在努力实现这一目标;

{
id:"id", name: 'name', Tokens:[{name:"yes",expiry:'Today'}, {name:"Hello", expiry:"tomorow"}]
}

我模拟了这样一个类

Class sample
{
[BSON]
public string id{get; set;}
public string name{get; set;}
public TokensCollection[] tokens(get; set;}
}

public class TokensCollection
{
public string name{get;set;}
public string expiry{get;set;}
}

在存储库中,我正尝试像这样初始化,

Sample sample1 = new Sample{
id = ObjectId.GenerateNewId().ToString();
name = "name";
//Best way to model this? any pointers?
for (int index =1; index <=2; index++)
{
tokens[index].name = "me";
tokens[index].expiry = "Today"
}

collection.insert(sample1);

有人可以帮我解决这个问题吗?

最佳答案

我最初在 MongoDb CSharp Google Group 上回答了您的问题这是任何有类似问题的人的例子;

using System;
using System.Collections.Generic;
using System.Linq;

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

using MongoDB.Driver;
using MongoDB.Driver.Linq;

namespace Test.ConsoleApp
{

public class Sample
{

[BsonId]
public ObjectId Id { get; private set; }
public string Name { get; set; }
public List<Token> Tokens { get; set; }

public Sample()
{
Id = ObjectId.GenerateNewId();
Tokens = new List<Token>();
}

}

public class Token
{
public string Name { get; set; }
public string Expiry { get; set; }
}


public class Program
{
static void Main(string[] args)
{
var server = MongoServer.Create("mongodb://localhost/database?safe=true");
var database = server.GetDatabase("test");
var samplesCollection = database.GetCollection<Sample>("samples");

Console.WriteLine("Creating Sample #1 ... ");

var sample1 = new Sample();
sample1.Name = "Sample #1";
sample1.Tokens.Add(new Token() { Name = "Name #1", Expiry = "Today" });

Console.WriteLine("Creating Sample #2 ... ");

var sample2 = new Sample();
sample2.Name = "Sample #2";
sample2.Tokens.Add(new Token() { Name = "Name #2", Expiry = "Tomorrow" });
sample2.Tokens.Add(new Token() { Name = "Name #3", Expiry = "Next Tuesday" });

Console.WriteLine("Saving Sample #1 and #2 ... ");

samplesCollection.Save(sample1);
samplesCollection.Save(sample2);

Console.WriteLine("Fetching Sample #1 and #2 ... ");

var sampleOneFromDb = samplesCollection.AsQueryable<Sample>().Where(c => c.Name.Contains("Sample #1"));

Console.WriteLine("Sample #1 From DB - {0}", sampleOneFromDb.ToJson());
Console.ReadLine();

}
}
}

关于c# - 在 C# 中建模 mongodb 子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12872262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com