简体   繁体   中英

unable to insert object into collection in monogoDB using c#

i am trying to insert an object into a database collection in Mongodb from C# .Net Core. It keeps giving me this error and i dont know what to do anymore, please help.

Object Class:

 [BsonDiscriminator("Company")]
public class Company
    {
    [BsonId]
    public ObjectId ID { get; set; }

        [BsonElement("CompanyId")]
        public int CompanyID { get; set; }

        [BsonElement("AccountNumber")]
        public string AccountNumber { get; set; }

        [BsonElement("BankId")]
        public int BankID { get; set; }
    }

Database connection class:

 public class DatabaseConnection
{
    static string connectionString = "mongodb://localhost:27017";
    public  DatabaseConnection()
    {

    }

    public IMongoDatabase DatabaseConnect()
    {

        return new MongoClient(connectionString).GetDatabase("FlourishDB");
    }


}

Action Class:

 public static void AddIntoDatabase(this Object obj)
    {
        try
        {
            IMongoCollection<Company> symbolcollection = new DatabaseConnection().DatabaseConnect().GetCollection<Company>("Company");

            Company c = (Company)obj;
            symbolcollection.InsertOne(c);

        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

Console Line:

 static void Main(string[] args)
    {
        new Company() { AccountNumber = "101010" }.AddIntoDatabase();
        Console.WriteLine("Completed succesfully");
        Console.ReadLine();
    }

Error Message achieved: Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Your code works perfectly fine with MongoDB Driver of latest 2.5.0 version. However I get the same error when using versions prior to 2.4.0.

So to fix your problem, upgrade used version of MongoDB driver to 2.4.0 or 2.5.0.

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