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

时间:2015-01-07 10:56:47

标签: 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
{
    public string Id {get;set;}
    public string Name {get;set;}
}

将用于存储在MongoDB中的另一个Dll就像这样(为了解耦原因,它是一个自己的dll):

public class TestMongo : Test
{
    static TestMongo()
    {
        //using this instead of attributes above every needed property. will avoid dependencies to mongodb.
        BsonClassMap.RegisterClassMap<Test>(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);
        });
    }
}

我正在以编程方式将属性添加到属性中,以确保在使用Test类时我没有依赖Mongo。

现在我需要为每个创建的SubTest-Element自动创建一个Id。 我试图在TestMongo-Constructor中添加另一个地图,但它不起作用:

...
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);
 });

当然我可以在将它写入mongo之前迭代所有SubTest-Elements但我更愿意让c#-driver为我做这件事。

我有办法做到这一点吗?

1 个答案:

答案 0 :(得分:2)

这种方式使用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();
    }
}

在app app startup注册序列化程序:

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"
            }
        ]
    ]
}