情况: 语言:C#使用C#驱动程序 我有一个包含List作为属性的模型。该List可以包含3个不同模型中的一个,它们都继承BaseModelClass。为了帮助序列化这种情况,Mongo添加_t来识别实际使用的模型。对于我们来说,这是一个问题,因为_t占据了大量的空间。我是一个卑微的开发者,我已经要求更多空间和ram,他们告诉我在没有额外空间的情况下解决它。所以我坐下来编写一个自定义序列化程序,处理不同的类型,而不是写一个_t到BSONDocument。在我开始对序列化进行单元测试之前,我认为一切都很棒。我开始得到“当ContextType是数组时,只能调用ReadEndArray,而不是当ContextType是Document时。”
非常感谢任何建议或建议。
这是我到目前为止的代码......
< --------- Collection Model --------------------->
[BsonCollectionName("calls")]
[BsonIgnoreExtraElements]
public class Call
{
[BsonId]
public CallId _id { get; set; }
[BsonElement("responses")]
[BsonIgnoreIfNull]
public IList<DataRecord> Responses { get; set; }
}
&lt; ----------基础数据记录------------------&gt;
[BsonSerializer(typeof(DataRecordSerializer))]
public abstract class DataRecord
{
[BsonElement("key")]
public string Key { get; set; }
}
&lt; -----------实际数据记录示例-----------------&gt;
[BsonSerializer(typeof(DataRecordSerializer))]
public class DataRecordInt : DataRecord
{
[BsonElement("value")]
public int Value { get; set; }
}
[BsonSerializer(typeof(DataRecordSerializer))]
public class DataRecordDateTime : DataRecord
{
[BsonElement("value")]
public DateTime? Value { get; set; }
}
&lt; ---------------单元测试触发解串器-----------------&gt;
//Arrange
var bsonDocument = TestResources.SampleCallJson;
//Act
var result = BsonSerializer.Deserialize<Call>(bsonDocument);
//Assert
Assert.IsTrue(true);
&LT; ----------------串行-----------------&GT;
public class DataRecordSerializer : IBsonSerializer
{
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
//Entrance Criteria
if(nominalType != typeof(DataRecord)) throw new BsonSerializationException("Must be of base type DataRecord.");
if(bsonReader.GetCurrentBsonType() != BsonType.Document) throw new BsonSerializationException("Must be of type Document.");
bsonReader.ReadStartDocument();
var key = bsonReader.ReadString("key");
bsonReader.FindElement("value");
var bsonType = bsonReader.CurrentBsonType;
if (bsonType == BsonType.DateTime)
{
return DeserializeDataRecordDateTime(bsonReader, key);
}
return bsonType == BsonType.Int32 ? DeserializeDataRecordInt(bsonReader, key) : DeserializeDataRecordString(bsonReader, key);
}
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
//Entrance Criteria
if (nominalType != typeof (DataRecord)) throw new BsonSerializationException("Must be of base type DataRecord.");
if (bsonReader.GetCurrentBsonType() != BsonType.Document) throw new BsonSerializationException("Must be of type Document.");
bsonReader.ReadStartDocument(); // Starts Reading and is able to pull data fine through this and the next few lines of code.
var key = bsonReader.ReadString("key");
if (actualType == typeof(DataRecordDateTime))
{
return DeserializeDataRecordDateTime(bsonReader, key);
}
return actualType == typeof(DataRecordInt) ? DeserializeDataRecordInt(bsonReader, key) : DeserializeDataRecordString(bsonReader, key); // Once it tries to return I am getting the following Error: ReadEndArray can only be called when ContextType is Array, not when ContextType is Document.
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
return new DocumentSerializationOptions
{
AllowDuplicateNames = false,
SerializeIdFirst = false
};
}
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
var currentType = value.GetType();
if (currentType == typeof (DataRecordInt))
{
SerializeDataRecordInt(bsonWriter, value);
return;
}
if (currentType == typeof(DataRecordDateTime))
{
SerializeDataRecordDateTime(bsonWriter, value);
return;
}
if (currentType == typeof(DataRecordString))
{
SerializeDataRecordString(bsonWriter, value);
}
}
private static object DeserializeDataRecordString(BsonReader bsonReader, string key)
{
var stringValue = bsonReader.ReadString();
var isCommentValue = false;
if (bsonReader.FindElement("iscomment"))
{
isCommentValue = bsonReader.ReadBoolean();
}
return new DataRecordString
{
Key = key,
Value = stringValue,
IsComment = isCommentValue
};
}
private static object DeserializeDataRecordInt(BsonReader bsonReader, string key)
{
var intValue = bsonReader.ReadInt32();
return new DataRecordInt
{
Key = key,
Value = intValue
};
}
private static object DeserializeDataRecordDateTime(BsonReader bsonReader, string key)
{
var dtValue = bsonReader.ReadDateTime();
var dateTimeValue = new BsonDateTime(dtValue).ToUniversalTime();
return new DataRecordDateTime
{
Key = key,
Value = dateTimeValue
};
}
private static void SerializeDataRecordString(BsonWriter bsonWriter, object value)
{
var stringRecord = (DataRecordString) value;
bsonWriter.WriteStartDocument();
var keyValue = stringRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
var valueValue = stringRecord.Value;
bsonWriter.WriteString("value", string.IsNullOrEmpty(valueValue) ? string.Empty : valueValue);
bsonWriter.WriteBoolean("iscomment", stringRecord.IsComment);
bsonWriter.WriteEndDocument();
}
private static void SerializeDataRecordDateTime(BsonWriter bsonWriter, object value)
{
var dateRecord = (DataRecordDateTime) value;
var millisecondsSinceEpoch = dateRecord.Value.HasValue
? BsonUtils.ToMillisecondsSinceEpoch(new DateTime(dateRecord.Value.Value.Ticks, DateTimeKind.Utc))
: 0;
bsonWriter.WriteStartDocument();
var keyValue = dateRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
if (millisecondsSinceEpoch != 0)
{
bsonWriter.WriteDateTime("value", millisecondsSinceEpoch);
}
else
{
bsonWriter.WriteString("value", string.Empty);
}
bsonWriter.WriteEndDocument();
}
private static void SerializeDataRecordInt(BsonWriter bsonWriter, object value)
{
var intRecord = (DataRecordInt) value;
bsonWriter.WriteStartDocument();
var keyValue = intRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
bsonWriter.WriteInt32("value", intRecord.Value);
bsonWriter.WriteEndDocument();
}
}
答案 0 :(得分:4)
此处还询问:https://groups.google.com/forum/#!topic/mongodb-user/iOeEXbUYbo4
我认为在这种情况下你最好的选择是使用自定义鉴别器约定。您可以在此处查看此示例:https://github.com/mongodb/mongo-csharp-driver/blob/v1.x/MongoDB.DriverUnitTests/Samples/MagicDiscriminatorTests.cs。虽然此示例基于文档中是否存在字段,但您可以轻松地将其基于字段的类型(BsonType.Int32,BsonType.Date等...)。
答案 1 :(得分:0)
基于@Craig Wilson的答案,要摆脱所有歧视因素,您可以:
public class NoDiscriminatorConvention : IDiscriminatorConvention
{
public string ElementName => null;
public Type GetActualType(IBsonReader bsonReader, Type nominalType) => nominalType;
public BsonValue GetDiscriminator(Type nominalType, Type actualType) => null;
}
并注册:
BsonSerializer.RegisterDiscriminatorConvention(typeof(BaseEntity), new NoDiscriminatorConvention());