Sunday 22 June 2014

C# MongoDb setup configuration for ASP.NET, ASP.NET MVC AND ASP.NET WEB API Applications


In this post, I will explain a basic mongoDB sample setup project for different .net applications (ASP.NET,ASP.NET MVC/WEB API etc.). You can use this code as base to mongoDB integration to your application.

Project Structure:
- Data
contains the mongoDB bootstrap logic for .net applications
- CSharpMongoDBSetup
C# console application as client application for mongoDB integration.

In Data project we have BaseEntity.cs which contains the core logic of mongoDB bootstrap/setup. On line # 185 we have repository section where we initialize the repository, and implemented the basic repository methods like get, delete and count etc.

 #region Repository

        [BsonIgnore, JsonIgnore]
        public static readonly string TypeName = typeof(TEntity).Name;

        [BsonIgnore, JsonIgnore]
        private static object _repoSync = new object();
        [BsonIgnore, JsonIgnore]
        private static MongoRepository<TEntity> _myRepository = null;
        /// <summary>
        /// Gets the repository used for manipulating this instance.
        /// </summary>
        [BsonIgnore, JsonIgnore]
        public static MongoRepository<TEntity> Repository
        {
            get
            {
                if (_myRepository != null)
                    return _myRepository;

                lock (_repoSync)
                {
                    if (_myRepository != null)
                        return _myRepository;

                    var myRepo = typeof(TEntity)
                        .GetCustomAttributes(typeof(RepositoryAttribute), true)
                        .OfType<RepositoryAttribute>()
                        .FirstOrDefault();

                    string cName = (myRepo == null || string.IsNullOrWhiteSpace(myRepo.ConnectionStringName)) ? "MongoServerSettings" : myRepo.ConnectionStringName;
                    var connString = ConfigurationManager.ConnectionStrings[cName];
                    if (connString == null)
                        throw new ApplicationException(string.Format("MongoDB connection string '{0}' is missing from configuration", cName));
                    _myRepository = new MongoRepository<TEntity>(connString.ConnectionString, TypeName);
                }

                return _myRepository;
            }
        }//end: Repository

        /// <summary>
        /// Gets the entity by its Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns>The entity found by the Id or <c>null</c> if no entity was found by that id.</returns>
        public static TEntity GetById(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                return default(TEntity);

            return Repository.GetById(id.ToLowerInvariant());

        }

        /// <summary>
        /// Gets a queryable version of this entity type's repository for manual searching.
        /// </summary>
        /// <returns>A queryable version of this entity type's repository for manual searching.</returns>
        public static IQueryable<TEntity> AsQueryable()
        {
            return Repository.AsQueryable();
        }

        /// <summary>
        /// Counts the total entities in the repository.
        /// </summary>
        /// <returns>Count of entities in the collection.</returns>
        public static long Count()
        {
            return Repository.Count();
        }

        /// <summary>
        /// Deletes an entity from the repository by its id.
        /// </summary>
        /// <param name="id">The entity's id.</param>
        /// <exception cref="201"></exception>
        public static void Delete(string id)
        {
            var entity = GetById(id);
            if (entity != null)
                entity.Delete();
        }

        /// <summary>
        /// Deletes all entities in the repository.
        /// </summary>
        public static void DeleteAll()
        {
            Repository.DeleteAll();
        }

        /// <summary>
        /// Checks if the entity exists for given predicate.
        /// </summary>
        /// <param name="predicate">The expression.</param>
        /// <returns>True when an entity matching the predicate exists, false otherwise.</returns>
        public static bool Exists(Expression<Func<TEntity, bool>> predicate)
        {
            return Repository.Exists(predicate);
        }

        #endregion

 On line #66 we have implemented few public events for example "saving" which is useful to validate entity before actually saving the data.

 #region Public Events

        /// <summary>
        /// Event is called before this entity of type TEntity is saved. This is useful
        /// for additional validation, etc. and may be canceled.
        /// </summary>
        public event Action<object, CancelableEntityEventArgs<TEntity>> Saving;

        /// <summary>
        /// Event is called after an entity has been saved, passing the newly saved entity.
        /// </summary>
        public event Action<object, EntityEventArgs<TEntity>> Saved;

        /// <summary>
        /// Event is called before this entity of type TEntity is deleted. This is useful
        /// for additional validation, etc. and may be canceled.
        /// </summary>
        public event Action<object, CancelableEntityEventArgs<TEntity>> Deleting;

        /// <summary>
        /// Event is called after an entity has been saved, passing the recently deleted entity.
        /// </summary>
        public event Action<object, EntityEventArgs<TEntity>> Deleted;

        #endregion


Furthermore, all domain objects/collections which going to persist inherit from BaseEntity.cs, to use the logic implemented in BaseEntity.cs. For example User.cs in this sample inherits from BaseEntity.cs, and in console application you can see that we are able to use save method for user collection.

I hope that it will help people to get going with mongoDB.

Code Sample:
https://github.com/aamir-poswal/CSharpMongoDbConfigurationSetup

No comments:

Post a Comment