简体   繁体   中英

MongoDriver Deserialization

I have a issue with MongoDriver. I have a inherited class from Class1 a mongo repository for Class1. For example:

public class Class1: EntityBase
{
    [BsonElement("a")]
    public A Attr { get; set; } 
}

public class Class2: Class1
{
    [BsonElement("d")]
    public IList<float> D{ get; set; }

    [BsonElement("p")]
    public int P{ get; set; }

    [BsonElement("s")]
    public int S{ get; set; }
}

And I have a several projects in my solution. I have project with repositories where the classes are located. When I try to insert and load a Class2 instance in a first project so everything's fine. But when I try to do same thing in the other:

Element 'd' does not match any field or property of class Class1.

Both projects refers to the repository project (dll). What can be wrong?

I found the solotuion. Class1 should have mongo attribute [BsonKnownTypes]

So Class1 should looks like:

[BsonKnownTypes(typeof(Class2))]
public class Class1: EntityBase
{
    [BsonElement("a")]
    public A Attr { get; set; } 
}

The reason why one project works and the other one throws exception was simple. The first one usel Class2 and inserts an instance to repository so mongoDriver register inherited type. After that it was able to deserialized the stored instance to Class2 . The second one had no idea about Class2 so it tried to deserialized object to Class1 and it throwed the exception about uknown element 'd'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM