我是 mongo DB 的新手,并且拥有实现相同接口的不同类的对象。我将这些对象存储在工作正常的 mongo DB 中。问题是这个对象的反序列化。
这是我的界面和类:
public interface IEvent
{ ... }
[Serializable, JsonObject]
[BsonDiscriminator(Required = true)]
[BsonKnownTypes(typeof(CloudBaseEvent))]
public class BaseEvent: IEvent
{...}
[Serializable, JsonObject]
[BsonDiscriminator(Required = true)]
[BsonKnownTypes(typeof(CloudRenameEvent))]
public abstract class CloudBaseEvent : BaseEvent, IEvent
{
[Serializable, JsonObject]
[BsonDiscriminator(Required = true)]
public class CloudRenameEvent : CloudBaseEvent, IEvent
{ ... }
public class EventLog
{
[BsonId]
public string EventID { get; set; }
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
public IEvent Event { get; set; }
对于过滤,我需要检查 e.Event.Account。这里出现错误
无法确定 e => e.Event.Account 的序列化信息
似乎 e.Event 的反序列化不起作用:
internal class MyRepository
{
private readonly IMongoDbRepository<Types.Models.EventLog> _mongoDb;
/// <summary>
/// Static constructor, initializes the MongoDB ClassMap.
/// </summary>
static MyRepository()
{
BsonClassMap.RegisterClassMap<Types.Models.EventLog>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
BsonClassMap.RegisterClassMap<BaseEvent>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
BsonClassMap.RegisterClassMap<CloudRenameEvent>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
MongoDefaults.GuidRepresentation = GuidRepresentation.Standard;
}
public async Task<EventLog.Types.Models.EventLog> GetEventLogAsync(string eventId)
{
var collection = await _mongoDb.GetCollectionAsync();
var filter = GetCustomerEventLogFilter(eventId);
var res = await collection.Aggregate()
//Here occurs the error
.Match(filter)
.FirstOrDefaultAsync();
return res;
}
private FilterDefinition<Types.Models.EventLog> GetCustomerEventLogFilter(string eventId)
{
var filters = new List<FilterDefinition<Types.Models.EventLog>>
{
Builders<Types.Models.EventLog>.Filter.Eq(e => e.Event.Account, Account),
};
return Builders<Types.Models.EventLog>.Filter.And(filters);
}
}
如果我添加注释
[BsonSerializer(typeof(ImpliedImplementationInterfaceSerializer<IEvent, BaseEvent>))]
以上
public IEvent Event { get; set; }
序列化有效,但我必须选择类(例如 BaseEvent)。这必须自动工作。