Search code examples
c#sql-servermongodb.net-core.net-core-2.0

Use Same Syntax for MongoDB and SQL with C# or Linq


Noticed MongoDB has different keywords, like InsertOne, ReplaceOne , etc. A point of Linq (Language Integrated Query), was to have a universal language where people can utilize dependency injection and swap between SQL or NoSQL without changing syntax heavily . SQL uses .Add() and Remove() .

Is there an easy way to make the two have similar syntax?

SQL:

https://learn.microsoft.com/en-us/ef/core/saving/basic

MongoDB:

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio

https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/

public BookService(IConfiguration config)
    {
        var client = new MongoClient(config.GetConnectionString("BookstoreDb"));
        var database = client.GetDatabase("BookstoreDb");
        _books = database.GetCollection<Book>("Books");
    }

    public List<Book> Get()
    {
        return _books.Find(book => true).ToList();
    }

    public Book Get(string id)
    {
        return _books.Find<Book>(book => book.Id == id).FirstOrDefault();
    }

    public Book Create(Book book)
    {
        _books.InsertOne(book);
        return book;
    }

    public void Update(string id, Book bookIn)
    {
        _books.ReplaceOne(book => book.Id == id, bookIn);
    }

    public void Remove(Book bookIn)
    {
        _books.DeleteOne(book => book.Id == bookIn.Id);
    }

    public void Remove(string id)
    {
        _books.DeleteOne(book => book.Id == id);
    }
}

Solution

  • I personally find the Mongodb c# driver a bit intimidating coming from a Entity Framework background.

    However, I've created an abstraction layer called MongoDAL which makes it quite easy to work with the Mongodb driver.

    It supports registering with ASP.Net Core dependency injection system or just use the static DB class to perform operations and write LINQ queries on any of your collections in a fully type safe manner. You can make your own repositories with it easily too. Don't have to deal with ObjectId or BsonDocument types either.