Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用c为Mongodb中的子文档创建ID#_C#_Mongodb_Mongodb .net Driver - Fatal编程技术网

C# 如何使用c为Mongodb中的子文档创建ID#

C# 如何使用c为Mongodb中的子文档创建ID#,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我正在尝试为mongodb中的子文档自动创建ID 我有以下课程: public class Test { public string Id {get;set;} public List<SubTest> SubTestList{get;set;} public Test() { SubTestList = new List<SubTest>(); } } public class SubTest { pu

我正在尝试为mongodb中的子文档自动创建ID

我有以下课程:

public class Test
{
    public string Id {get;set;}
    public List<SubTest> SubTestList{get;set;}

    public Test()
    {
        SubTestList = new List<SubTest>();
    }
}

public class SubTest
{
    public string Id {get;set;}
    public string Name {get;set;}
}
公共类测试
{
公共字符串Id{get;set;}
公共列表子测试列表{get;set;}
公开考试()
{
SubTestList=新列表();
}
}
公共类子测验
{
公共字符串Id{get;set;}
公共字符串名称{get;set;}
}
另一个用于存储在MongoDB中的Dll如下所示(出于解耦原因,它是自己的Dll):

公共类TestMongo:Test
{
静态TestMongo()
{
//使用此属性而不是每个所需属性之上的属性。将避免对mongodb的依赖。
BsonClassMap.RegisterClassMap(cm=>
{
cm.AutoMap();
//将属性“Id”注册为mongodb。
SetIdMember(cm.GetMemberMap(c=>c.Id).SetRepresentation(BsonType.ObjectId));
//将生成一个Id并设置Id属性,该属性是此类中的字符串。
cm.IdMemberMap.SetIdGenerator(StringObjectiveGenerator.Instance);
});
}
}
我以编程方式将属性添加到属性中,以确保在使用测试类时不依赖Mongo

现在我需要为每个创建的子测试元素自动创建一个Id。 我试图在TestMongo构造函数中添加另一个映射,但没有成功:

...
BsonClassMap.RegisterClassMap<SubTest>(cm =>
{
    cm.AutoMap();

    //register property "Id" to be the mongodb.
    cm.SetIdMember(cm.GetMemberMap(c => c.Id).SetRepresentation(BsonType.ObjectId));

    //Will generate an Id and set the Id-Property which is a string in this class.
    cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
 });
。。。
BsonClassMap.RegisterClassMap(cm=>
{
cm.AutoMap();
//将属性“Id”注册为mongodb。
SetIdMember(cm.GetMemberMap(c=>c.Id).SetRepresentation(BsonType.ObjectId));
//将生成一个Id并设置Id属性,该属性是此类中的字符串。
cm.IdMemberMap.SetIdGenerator(StringObjectiveGenerator.Instance);
});
当然,在将其写入mongo之前,我可以迭代所有子测试元素,但我更愿意让c#驱动程序为我这样做


有什么方法可以做到这一点吗?

这种方法使用mongo的自定义对象序列化程序:

1-编写序列化程序:

public class TestSerialzer : IBsonSerializer
{
    public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
    {
        return BsonSerializer.Deserialize<Test>(bsonReader);
    }

    public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        throw new NotImplementedException();
    }

    public IBsonSerializationOptions GetDefaultSerializationOptions()
    {
        throw new NotImplementedException();
    }

    public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {            
        var test = (Test)value;
        bsonWriter.WriteStartDocument();

        if (string.IsNullOrEmpty(test.Id)) test.Id = ObjectId.GenerateNewId().ToString();

        bsonWriter.WriteString("_id", test.Id);

        foreach (var nestedObj in test.SubTestList)
        {
            if (string.IsNullOrEmpty(nestedObj.Id)) nestedObj.Id = ObjectId.GenerateNewId().ToString();
        }

        bsonWriter.WriteStartArray("SubTestList");
        BsonSerializer.Serialize(bsonWriter, test.SubTestList);

        bsonWriter.WriteEndArray();
        bsonWriter.WriteEndDocument();
    }
}
对于试验对象,如下所示:

var test = new Test
{
    SubTestList = new List<SubTest>
    {
      new SubTest
      {
          Name = "Name1",
      },
      new SubTest
      {
        Name  = "Name2",
      },
    },
};
collection.Insert(test);

我不认为mongodb提供了它。您可能必须使用c#drive方法来生成mongodb IDS我认为最好的自动方法是为您的类编写自定义序列化程序,但这对您不起作用
var sub=new SubTest{Name=“whatever”,Id=ObjectId.GenerateNewId()}
?@steen No,因为定义子测试类的dll对mongo类(ObjectId)一无所知。我可能只是为子文档创建自己的集合,并创建一个引用…@Disposer,这似乎是合乎逻辑的方式。一个例子就是一个答案。这不仅仅是为了捕获类
子测试的类实例,还是实现公共接口的东西?我以为可以,但我现在没有穿上我的C#靴,也没有时间测试它。似乎合乎逻辑,但你应该能够反省。我相信你可以用Java做例子。
BsonSerializer.RegisterSerializer(typeof(Test), new TestSerialzer());
var test = new Test
{
    SubTestList = new List<SubTest>
    {
      new SubTest
      {
          Name = "Name1",
      },
      new SubTest
      {
        Name  = "Name2",
      },
    },
};
collection.Insert(test);
{
    "_id" : "54ad5b25e8b07a214c390ccf",
    "SubTestList" : [ 
        [ 
            {
                "_id" : "54ad5b25e8b07a214c390cd0",
                "Name" : "Name1"
            }, 
            {
                "_id" : "54ad5b25e8b07a214c390cd1",
                "Name" : "Name2"
            }
        ]
    ]
}