【发布时间】:2015-07-20 21:44:33
【问题描述】:
我已经为我的集合实现了带有基实体类的存储库模式。到目前为止,所有集合都有 _id 的 ObjectId 类型。在代码中,我需要将Id 表示为一个字符串。
EntityBase 类如下所示
public abstract class EntityBase
{
[BsonRepresentation(BsonType.ObjectId)]
public virtual string Id { get; set; }
}
这是映射:
BsonClassMap.RegisterClassMap<EntityBase>(cm =>
{
cm.AutoMap();
cm.MapIdProperty(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance);
cm.IdMemberMap.SetSerializer(new StringSerializer().WithRepresentation(BsonType.ObjectId));
});
现在我有一个语言集合,它的 ID 将是纯字符串,例如 en-GB。
{
"_id" : "en-GB",
"Term1" : "Translation 1",
"Term2" : "Translation 2"
}
Language 类继承 EntityBase 类
public class Language : EntityBase
{
[BsonExtraElements]
public IDictionary<string, object> Terms { get; set; }
public override string Id { get; set; }
}
问题是我能否以某种方式更改Id 仅针对Language 类的序列化方式?
我不想更改 EntityBase 类的行为,因为我有很多其他集合继承了 EntityBase。
更新
这是我尝试并得到异常的方法。不确定我尝试过的是否可行。
BsonClassMap.RegisterClassMap<Language>(cm =>
{
cm.AutoMap();
cm.MapExtraElementsMember(c => c.Terms);
cm.MapIdProperty(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance);
cm.IdMemberMap.SetSerializer(new StringSerializer().WithRepresentation(BsonType.String));
});
这是我得到的例外:
An exception of type 'System.ArgumentOutOfRangeException' occurred in MongoDB.Bson.dll but was not handled in user code
Additional information: The memberInfo argument must be for class Language, but was for class EntityBase.
at MongoDB.Bson.Serialization.BsonClassMap.EnsureMemberInfoIsForThisClass(MemberInfo memberInfo)
at MongoDB.Bson.Serialization.BsonClassMap.MapMember(MemberInfo memberInfo)
at MongoDB.Bson.Serialization.BsonClassMap`1.MapMember[TMember](Expression`1 memberLambda)
at MongoDB.Bson.Serialization.BsonClassMap`1.MapProperty[TMember](Expression`1 propertyLambda)
at MongoDB.Bson.Serialization.BsonClassMap`1.MapIdProperty[TMember](Expression`1 propertyLambda)
at Test.Utilities.MongoDbClassConfig.<>c.<Configure>b__0_1(BsonClassMap`1 cm) in F:\Development\Test\Utilities\MongoDbClassConfig.cs:line 23
at MongoDB.Bson.Serialization.BsonClassMap`1..ctor(Action`1 classMapInitializer)
at MongoDB.Bson.Serialization.BsonClassMap.RegisterClassMap[TClass](Action`1 classMapInitializer)
at Test.Utilities.MongoDbClassConfig.Configure() in F:\Development\Test\Utilities\MongoDbClassConfig.cs:line 20
at Test.Portal.BackEnd.Startup..ctor(IHostingEnvironment env) in F:\Development\Test\Startup.cs:line 43
【问题讨论】:
-
也许这是一种幼稚的做法。但是您能否在您的语言类中再次实现 Id 属性(覆盖基类的属性)。然后只为这个语言类添加一个特定的映射,并以你喜欢的方式处理序列化?
-
这是我尝试的第一件事。我遇到了一个异常,即 Id 属于
EntityBase类。 -
你不能创建 ID 属性
virtual并为Id的类型使用通用类型参数。然后在派生类中覆盖它? --- 而且,你需要使用[BsonId]-attribute,让它将Id识别为BSON-id。当您覆盖您的虚拟属性时,您的[BsonRepresentation(BsonType.ObjectId)]将不会被继承。
标签: c# mongodb mongodb-.net-driver