6

使用 BsonClassMap,是否可以映射域对象引用,同时保持域对象程序集持久无知(将public A Reference { get; set; }属性更改为下面public MongoDBRef Reference{ get; set; }的示例类B是不可接受的)。

对于这种情况,引用的对象不是同一聚合的一部分,不应存储为嵌套文档。

是否可以在这样的关系中映射两个域对象:

public class A
{
    public Guid Id {get; private set; }
}

public class B
{
    public Guid Id { get; private set; }
    public A Reference { get; set; }
}

进入如下文档结构:

// Collection for class A
{ _id: "11111111-1111-1111-1111-111111111111" }

// Collection class B
{ 
    _id: "22222222-2222-2222-2222-222222222222",
    reference_id: "11111111-1111-1111-1111-111111111111"
}

映射可能如下所示:

BsonClassMap.RegisterClassMap<A>(cm => 
{
    cm.MapIdProperty(c => c.Id)
        .SetIdGenerator(new GuidGenerator())
        .SetRepresentation(BsonType.String);
}

BsonClassMap.RegisterClassMap<B>(cm => 
{
    cm.MapIdProperty(c => c.Id)
        .SetIdGenerator(new GuidGenerator())
        .SetRepresentation(BsonType.String);

    // How do I map the B.Reference to a manual reference (like 
    // the sample doc structure above) or possibly as a DBRef?
}

那么,在不更改模型的情况下,我如何将Reference属性映射到 object A,从 objectB作为 DBRef 或作为手动引用(如上面的示例文档结构)?

Is this possible using BsonClassMap? Or in order to use BsonClassMap and keep my domain assembly persistent ignorant, do I need to change the model to something like:

public class A
{
    public Guid Id {get; private set; }
}

public class B
{
    public Guid Id { get; private set; }
    public Guid ReferenceId { get; set; } // Don't reference the object directly,
                                          // just store the Guid to the 
                                          // referenced object.
}
4

1 回答 1

3

I posed this same question to the mongodb-csharp user group and got a response from craiggwilson:

You'll need to change your ReferenceProperty to ReferencePropertyId. We do not support lazy-loading (or eager-loading) of referenced documents.

Since A is not the aggregate for B, then this actually makes more sense when discussing in these terms. Generally, it is unnecessary for a referenced aggregate (B) to be loaded in order to process the referencing aggregate (A). It might be that you do indeed need some information from B. In this case, think about denormalizing a little and creating a true entity (BSummary) whose aggregate is A. This would make sense if some of the summary information is immutable or changes infrequently.

于 2013-02-19T02:57:13.697 回答