Skip to content

A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management

License

Notifications You must be signed in to change notification settings

dj-nitehawk/MongoDB.Entities

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

84 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MongoDB.Entities

It is a data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management features. The library aims to tuck away the complexity of the official C# driver and help fast-track application development with MongoDB. Both Document and Relational type data modelling is possible. Developers coming from an Entity Framework background will feel right at home.

Install

install the nuget package with command:

Install-Package MongoDB.Entities

Initialize

first import the package with using MongoDB.Entities;

then initialize as below according to the platform you're using.

ASP.Net Core (Basic initialization):

add the following inside ConfigureServices method of Startup.cs file:

  services.AddMongoDBEntities("DatabaseName","HostAddress",PortNumber);

ASP.Net Core (Advanced initialization):

add the following inside ConfigureServices method of Startup.cs file:

  services.AddMongoDBEntities(
      new MongoClientSettings()
      {
        Server = 
            new MongoServerAddress("HostAddress", PortNumber),
        Credential = 
            MongoCredential.CreateCredential("DatabaseName", "UserName", "Password")
       },
       "DatabaseName");

.Net Core (Basic initialization):

  new DB("bookshop");

.Net Core (Advanced initialization):

  new DB(new MongoClientSettings()
  {
      Server = 
          new MongoServerAddress("localhost", 27017),
      Credential = 
          MongoCredential.CreateCredential("bookshop", "username", "password")
  }, "bookshop");

Entities

Creating entities:

create your entities by inheriting the Entity base class.

    public class Book : Entity
    {
        public string Title { get; set; }
    }

Ignoring properties:

if there are properties of entities you don't want persisted to mongodb, simply use the IgnoreAttribute

    public class Book : Entity
    {
        [Ignore]
        public string SomeProperty { get; set; }
    }

Saving entities:

call Save() on any entity to save the changes. new entities are automatically assigned an ID when they are persisted to the database.

    var book = new Book { Title = "The Power Of Now" }; 
    book.Save();

Embedding entities as documents:

to store an unlinked copy of an entity, call the ToDocument() method. doing so will store an independant duplicate of the original entity that has no relationship to the original entity.

    book.Author = author.ToDocument();
    book.OtherAuthors = (new Author[] { author2, author3 }).ToDocuments();

Deleting entities:

    book.OtherAuthors.DeleteAll()
    book.Delete();

to delete entities in bulk, use a lambda expression as follows:

    DB.Delete<Book>(b => b.Title.Contains("Trump"));

Relationships (Embedded)

One-to-one:

    var author = new Author { Name = "Eckhart Tolle" }
    author.Save();
    book.Author = author;
    book.Save()

as mentioned earlier, calling Save() persists author to the "Authors" collection in the database. it is also stored in book.Author property. so, the author entity now lives in two locations (in the collection and also inside the book entity) and are linked by the ID. if the goal is to embed something as an independant/unlinked document, it is best to use a class that does not inherit from the Entity class or simply use the .ToDocument() method of an entity as explained earlier.

One-to-many:

    book.OtherAuthors = new Author[] { author1, author2 };
    book.Save();

Tip: If you are going to store more than a handful of entities within another entity, it is best to store them by reference as described below.

Relationships (Referenced)

referenced relationships require a bit of special handling. a one-to-one relationship is defined by using the One<Book,Author> class and one-to-many relationships are defined by using the Many<Book,Author> class. it is also a good idea to initialize the Many<> properties with the Initialize() method as shown below in order to avoid null-reference exceptions during runtime.

    public class Book : Entity
    {
        public One<Author> MainAuthor { get; set; }
        public Many<Book,Author> Authors { get; set; }
        
        public Book() => Authors = Authors.Initialize(this);
    }

One-to-one:

call the ToReference() method of the entity you want to store as a reference like so:

    book.MainAuthor = author.ToReference();
    book.Save();

One-to-many:

    book.Authors.Add(author);
    book.Authors.Remove(author);

there's no need to call book.Save() because references are automatically created and saved using special joining collections in the form of Book_Author in the database. you don't have to pay any attention to these special collections unless you rename your entities. for ex: if you rename the Book entity to AwesomeBook just rename the corresponding join collection from Book_Author to AwesomeBook_Author in order to get the references working again. also if you delete an entity that is referenced somewhere in the database, all references pointing to that entity is automatically deleted.

ToEntity() shortcut:

a reference can be turned back in to an entity with the ToEntity() method.

    var author = book.MainAuthor.ToEntity();
    var author = book.Authors.Collection().FirstOrDefault().ToEntity();

Queries

data can be queried using LINQ or lambda expressions. most LINQ operations are available. see the mongodb c# driver linq documentation for more details.

Entity collections:

    var author = (from a in DB.Collection<Author>()
                  where a.Name.Contains("Eckhart")
                  select a).FirstOrDefault();

Reference collections:

    var authors = (from a in book.Authors.Collection()
                   select a).ToArray();

Shortcut for collections:

    var authorsQueryable = from a in author.Collection()
                           select a;

the .Collection() method of entities and references return an IQueryable which you can write queries against.

Async Support

async overloads are available for all provided methods.

in order to write async queries against collections, make sure to import the mongodb linq extensions and write queries as follows:

    using MongoDB.Driver;
    using MongoDB.Driver.Linq;
    var lastAuthor = await (from a in author.Collection()
                            orderby a.ModifiedOn descending
                            select a).FirstOrDefaultAsync();

Schema Changes

be mindful when changing the schema of your entities. the documents/entities stored in mongodb are always overwritten with the current schema/ shape of your entities. for example:

Old schema:
    public class Book : Entity
    {
        public string Title { get; set; }
        public int Price { get; set; }
    }
New schema:
    public class Book : Entity
    {
        public string Title { get; set; }
        public int SellingPrice { get; set; }
    }

the data stored in Price will be lost if you do not manually handle the transfer of data from the old property to the new property upon saving.

Examples

to see working examples please click here

to see this library used in a real-world application, check the ASP.Net Core WebAPI project click here

Donations

if this library has made your life easier and you'd like to express your gratitude, you can donate a couple of bucks via paypal by clicking the button below: