4

I'm trying to get familiar with writing to MongoDB from c# programs. I've set up my code following suggestions from http://mongodb.github.io/mongo-csharp-driver/1.11/getting_started/

I'm trying to run this program but getting this error "'MongoDB.Driver.MongoClient' does not contain a definition for 'GetServer' and no extension method 'GetServer' accepting a first argument of type 'MongoDB.Driver.MongoClient' could be found". May I get some help?

Thanks in advance, Tien.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
//Additionally, you will frequently add one or more of these using statements:
//using MongoDB.Driver.Builders; //Error rebuilding when this statement is active: "Using the generic type 'MongoDB.Driver.Builders<TDocument>' requires 1 type arguments
//using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
//using MongoDB.Driver.MongoClient; //Error rebuilding when this statement is active "A using namespace directive can only be applied to namespaces; 'MongoDB.Driver.MongoClient' is a type not a namespace 

namespace write2MongoDb
{
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }


class Program
{
    static void Main(string[] args)
    {
        #region Full Sample Program
        var connectionString = "mongodb://localhost";
        var client = new MongoClient(connectionString);
        var server = client.GetServer();
        var database = server.GetDatabase("test");
        var collection = database.GetCollection<Entity>("entities");

        var entity = new Entity { Name = "Tom" };
        collection.Insert(entity);
        var id = entity.Id;

        var query = Query<Entity>.EQ(e => e.Id, id);
        entity = collection.FindOne(query);

        entity.Name = "Dick";
        collection.Save(entity);

        var update = Update<Entity>.Set(e => e.Name, "Harry");
        collection.Update(query, update);

        collection.Remove(query);


        #endregion


        Console.ReadKey();
    }
}

}

Tien
  • 159
  • 1
  • 3
  • 10
  • 2
    Possible duplicate of [C# MongoDB.Driver GetServer is Gone, What Now?](http://stackoverflow.com/questions/29457098/c-sharp-mongodb-driver-getserver-is-gone-what-now) – Tinwor Nov 05 '16 at 18:16

1 Answers1

3

GetServer() has been deprecated, retrieve the database from the client like so:

var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");
Bryan
  • 213
  • 1
  • 11