Mongodb-当属性具有接口返回类型时如何反序列化 [英] Mongodb - how to deserialze when a property has an Interface return type

查看:420
本文介绍了Mongodb-当属性具有接口返回类型时如何反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免在数据层和使用此层的客户端代码之间引入任何依赖关系,但是在尝试使用Mongo(使用MongoRepository)进行操作时遇到了一些问题

I'm attempting to avoid introducing any dependencies between my Data layer and client code that makes use of this layer, but am running into some problems when attempting to do this with Mongo (using the MongoRepository)

MongoRepository显示了一些示例,您可以在这些示例中创建反映数据结构的Types,并在需要时继承Entity.例如

MongoRepository shows examples where you create Types that reflect your data structure, and inherit Entity where required. Eg.

[CollectionName("track")]
public class Track : Entity  
{
    public string name { get; set; }
    public string hash { get; set; }

    public Artist artist { get; set; }
    public List<Publish> published {get; set;}
    public List<Occurence> occurence  {get; set;}
}

为了在我的客户端代码中使用它们,我想用Interfaces替换Mongo特定的类型,例如:

In order to make use of these in my client code, I'd like to replace the Mongo-specific types with Interfaces, e.g:

[CollectionName("track")]
public class Track : Entity, ITrackEntity 
{
    public string name { get; set; }
    public string hash { get; set; }

    public IArtistEntity artist { get; set; }
    public List<IPublishEntity> published {get; set;}
    public List<IOccurenceEntity> occurence  {get; set;}
}

但是,Mongo驱动程序不知道如何处理这些接口,我可以理解地收到以下错误:

However, the Mongo driver doesn't know how to treat these interfaces, and I understandably get the following error:

反序列化类sf.data.mongodb.entities.Track的artist属性时发生错误:找不到类型为sf.data.IArtistEntity的序列化程序. ---> MongoDB.Bson.BsonSerializationException:找不到类型为sf.data.IArtistEntity的序列化程序.

有人对我该如何处理有任何建议吗?

Does anyone have any suggestions about how I should approach this?

推荐答案

好的-因此,我找到了自己的问题的答案-并认为如果有人遇到类似问题,我会分享

Okay - so I found the answer to my own question - and thought I'd share in case anyone has a similar problem

我正在寻找的功能是 BsonClassMap.RegisterClassMap

这使您可以显式定义域类的属性/字段应进行序列化/反序列化(请注意,它会替换所有自动映射-您需要定义要包括的所有字段/属性).它解决了反序列化为具有接口类型的属性的问题,而没有更多问题.

This allows you to explicitly define which properties / fields of your domain classes should be serialized / deserialized (note it replaces any automapping - you need to define all fields / properties you wish to include). It resolved the issue of deserializing to a property with an Interface type with no further problems.

BsonClassMap.RegisterClassMap<Track>(cm =>
{
    cm.MapProperty<IArtistEntity>(c => (IArtistEntity)c.Artist);
    cm.MapProperty<List<IOccurenceEntity>>(c => (List<IOccurenceEntity>)c.Occurence);
    cm.MapProperty(c => c.hash);
    cm.MapProperty(c => c.name);
    cm.MapProperty(c => c.published);

});

这篇关于Mongodb-当属性具有接口返回类型时如何反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆