Mongo DB BSON:无法确定接口(C#)的序列化信息

时间:2019-03-15 15:04:57

标签: c# mongodb bson mongodb.driver

我是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)。这必须自动工作。

1 个答案:

答案 0 :(得分:1)

我想解决此问题:

显然,使用接口时无法反序列化。至少我无法使其正常工作。因此,我将EventLog.Event的类型从IEvent更改为BaseEvent,现在一切正常。

提示:此外,所有属性都应可读可写也很重要。除此之外,您还必须使用注释“ BsonKnownTypes”。