MongoDB cannot create an abstract class problem, Bsonclassmap.registerclassmap

Source: Internet
Author: User

Cannot create abstract class

We all know that abstract classes cannot be instantiated, that is, they cannot be new.

You experience this problem in the following situations:

1. The base class is an abstract class:

2. The base class is an interface:

Because of the nature of MongoDB, when you save a subclass of an abstract class or interface, a field "_t" is automatically mapped: that is, the subclass name, but when you read it, you must create a subclass, but because you do not know the subclass, you create an instance of the base class that cannot be created because the base class is an abstract class or interface.

Here's the solution:

We can meet the total people have met, so often summed up their own problems, convenient for posterity, generation of generation.

MongoDB has come to think of us:

namespaces: MongoDB.Bson.Serialization;

Main class: Bsonclassmap;

Main methods: Registerclassmap;

Bsonclassmap.registerclassmap<t> ();

Attention:

When you cannot determine the type of T, you can do the following:

foreach (var type in types)
{
BOOL Isregist = bsonclassmap.isclassmapregistered (type);
if (isregist) continue;
Bsonclassmap.registerclassmap (New Classmap (type));
}

Customizing a class inheritance Bsonclassmap

It is mainly inherited from its constructor function;

public class Classmap:bsonclassmap
{
Public Classmap (Type ClassType): Base (ClassType) {}
}

There is more than one solution to a problem, so try to solve it in a variety of ways to improve it.

Welcome you to propose a better solution, thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.