Ehsan Ghanbari

Experience, DotNet, Solutions

How to persist ValueObjects of DDD via Fluent Nhibernate

I'm not going to go throw the DDD concepts again in this article as I did before here, this post is just about how to persist the Value Objects of Domain Driven Design by Fluent NHibernate. first, create the basic configuration for Domain Driven Design (I'm using the way that I've learned in Pro Asp.net Design Pattern Book). create an interface and name it IAggregateRoot

 

    public interface IAggregateRoot
    {
    }

 

Then add the BusinessRule Class

 

    public class BusinessRule
    {
        private string _property;
        private string _rule;

        public BusinessRule(string property, string rule)
        {
            _rule = rule;
            _property = property;
        }
        public string Property
        {
            get { return _property; }
            set { _property = value; }
        }
        public string Rule
        {
            get { return _rule; }
            set { _rule = value; }
        }
    }

 

Now create the EntityBase and ValueObjectBase Classes

 

    public abstract class EntityBase<TId>
    {
        private readonly List<BusinessRule> _brokenRules = new List<BusinessRule>();
        public virtual TId Id { get; set; }
        protected abstract void Validate();
        protected internal virtual IEnumerable<BusinessRule> GetBrokenRules()
        {
            _brokenRules.Clear();
            Validate();
            return _brokenRules;
        }
        protected void AddBrokenRule(BusinessRule businessRule)
        {
            _brokenRules.Add(businessRule);
        }
        public override bool Equals(object entity)
        {
            return entity != null && entity is EntityBase<TId> && this == (EntityBase<TId>)entity;
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
        public static bool operator ==(EntityBase<TId> entity1, EntityBase<TId> entity2)
        {
            if ((object)entity1 == null && (object)entity2 == null)
            {
                return true;
            }
            if ((object)entity1 == null || (object)entity2 == null)
            {
                return false;
            }
            if (entity1.Id.ToString() == entity2.Id.ToString())
            {
                return false;
            }
            return false;
        }
        public static bool operator !=(EntityBase<TId> entity1, EntityBase<TId> entity2)
        {
            return (!(entity1 == entity2));
        }
    }

 

And then Value Object Base Class

 

    public abstract class ValueObjectBase
    {
        private readonly List<BusinessRule> _brokenRules = new List<BusinessRule>();
        protected ValueObjectBase() { }
        protected static bool EqualOperator(ValueObjectBase left, ValueObjectBase right)
        {
            if (ReferenceEquals(left, null) ^ ReferenceEquals(right, null))
            {
                return false;
            }
            return ReferenceEquals(left, null) || left.Equals(right);
        }
        protected abstract void Validate();

        public void ThrowExceptionIfInvalid()
        {
            _brokenRules.Clear();
            Validate();
            if (_brokenRules.Count <= 0) return;
            var issues = new StringBuilder();
            foreach (BusinessRule businessRule in _brokenRules)
            {
                issues.AppendLine(businessRule.Rule);
            }
        }
        protected void AddBrokenRule(BusinessRule businessRule)
        {
            _brokenRules.Add(businessRule);
        }
    }

 

Sorry, I'm not going to talk about the above configurations, but you can use them as a base configuration for DDD in every enterprise application. Now Add a class and name it Address (this is the same Value Object class that we are going to know how to persist in the repository)

 

   public class Address : ValueObjectBase
    {
        public Address(string city, string street, string zipCode)
        {
            ZipCode = zipCode;
            Street = street;
            City = city;
        }

        public string City { get; private set; }
        public string Street { get; private set; }
        public string ZipCode { get; private set; }

        protected override void Validate()
        {
            throw new NotImplementedException();
        }
    }

 

In DDD we have a repository for every aggregate, and having a value object without having an entity doesn't mean anything and also we have to make the properties as a private set because Value Object should be immutable. now add the customer class, this class is an entity and also Root of the aggregate

 

   public class Customer : EntityBase<Guid>, IAggregateRoot
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public Address Address { get; set; }

        protected override void Validate()
        {
            throw new NotImplementedException();
        }
    }

 

It's time to create the CustomerMapping and the goal of this post

 

   public class CustomerMapping : ClassMap<Customer>
    {
        public CustomerMapping()
        {
            Table("Customer");
            Not.LazyLoad();
            Id(c => c.Id).GeneratedBy.GuidComb();
            Map(c => c.UserName).Not.Nullable();
            Map(c => c.Password).Not.Nullable();
            Component(c => c.Address, a =>
                {
                    a.Map(x => x.City).Column("City").Not.Nullable();
                    a.Map(x => x.Street).Column("Column").Not.Nullable();
                    a.Map(x => x.ZipCode).Column("ZipCode").Not.Nullable();
                });
        }
    }

 

By using component of fluent NHibernate you can easily map the value object of DDD. Notice that this mapping in Database will be a table named Customer with id, userName, Password, city, Street, ZipCode fields.



Fluent Nhibernate Sample Project in Asp.net MVC

NHibernate is an ORM designed for Microsoft.Net, it's free and open source and it's a port of Java mapper to Dot Net. And fluent NHibernate is a separate version of NHibernate which lets you write your entities according to your business instead of starting from creating tables, Fluent NHibernate is just a fluent API for mapping classes with NHibernate. what an ORM does, is persisting object In database and then retrieving when it is needed, indeed it translates the object to the database and vice versa.

In Entity Framework, you use DbContext or objectContext(in earlier versions) to make configuration, in this case, Models or properties acts as a UnitOfWork pattern but In NHibernate by Using ISessionFactory Models are keep in a separate in-memory database. I'm going to show a simple NHibernate configuration in this article, Now let's start!

create a new MVC4 project and get the latest version of Fluent NHibernate by Nuget:

NH

Or you can go to the website and get the latest version and reference the Fluent NHibernate, now create a new class named Product : 

 

    public class Product
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Category Category { get; set; }
    }

 

 and then add the Category Class to your Model folder in your project :

 

    public class Category
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
    }

 

you should define the properties as virtual because of lazy loading(retrieving an object or so-called data from the database when it's needed is lazy loading) , now create two separate class for mapping this Model classes via Fluent NHibernate :

 

    public sealed class ProductMapping : ClassMap<Product>
    {
        public ProductMapping()
        {
            LazyLoad();
            Table("Product");
            Id(p => p.Id);
            Id(p => p.Id).GeneratedBy.Identity();
            Map(p => p.Name);
            References(p => p.Category);
        }
    }

    public sealed class CategoryMapping : ClassMap<Category>
    {
        public CategoryMapping()
        {
            LazyLoad();
            Table("Category");
            Id(c => c.Id);
            Id(c => c.Id).GeneratedBy.Identity();
            Map(c => c.Name);
        }
     }

 

Now the most important and goal of this article is about configuration class of Fluent NHibernate, create the class with this definition

 

    public class SessionFactory : IHttpModule
    {
        private static readonly ISessionFactory _SessionFactory;
        static SessionFactory()
        {
            _SessionFactory = CreateSessionFactory();
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }

        public void Dispose()
        {
        }

        public static ISession GetCurrentSession()
        {
            return _SessionFactory.GetCurrentSession();
        }

        private static void BeginRequest(object sender, EventArgs e)
        {
            ISession session = _SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        private static void EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(_SessionFactory);
            if (session == null) return;
            try
            {
                session.Transaction.Commit();
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
                session.Dispose();
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =>    c.FromConnectionStringWithKey("DefaultConnection")))
                           .Mappings(m => m.AutoMappings.Add(CreateMappings()))
                           .CurrentSessionContext<WebSessionContext>()
                           .BuildSessionFactory();
        }

        private static AutoPersistenceModel CreateMappings()
        {
            return AutoMap
                .Assembly(System.Reflection.Assembly.GetCallingAssembly())
                .Where(t => t.Namespace != null && t.Namespace.EndsWith("Models"))
                .Conventions.Setup(c => c.Add(DefaultCascade.SaveUpdate()));
        }
    }

 

Now Open Web.config file and set the connectionString tag :

 

<connectionStrings>
    <add name="DefaultConnection" connectionString="Server=EHSAN\EHSAN;Database=NhMvcDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

 

Notice that NhMvcDB is my database name and DefaultConnection is my connectionString Name and EHSAN\EHSAN is my SQL server instance name!

You should create the Repository class to talk to the database, to make it simple I just create the ProductRepository Class (Not a Generic class for using all entities), to do that add an Interface to your Model :

 

    public interface IProductRepository
    {
        void Add(Product product);
        Product Get(int id);
        void Remove(Product product);
        IEnumerable<Product> GetAll();
        IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId);
        IEnumerable<Category> GetAllCategoriesQuery();
    }

 

And then  implement the members in ProductRepository class like this

 

    public class ProductRepository : IProductRepository
    {
        private readonly ISession _session;

        public ProductRepository()
        {
            _session = SessionFactory.GetCurrentSession();
        }
        public void Add(Product product)
        {
            SessionFactory.GetCurrentSession().Save(product);
        }

        public Product Get(int id)
        {
            return SessionFactory.GetCurrentSession().Get<Product>(id);
        }

        public void Remove(Product product)
        {
            SessionFactory.GetCurrentSession().Delete(product);
        }

        public IEnumerable<Product> GetAll()
        {
            return _session.Query<Product>();
        }

        public IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId)
        {
            var products= _session.Query<Product>();
            var productsByCategory = from c in products
                                     where c.Id == categoryId
                                     select c;
            return productsByCategory;
        }

        public IEnumerable<Category> GetAllCategoriesQuery()
        {
            return _session.Query<Category>();
        }
    }

 

Now create the Service interface

 

    public interface IProductService
    {
        void AddProduct(Product product);
        void RemoveProduct(Product productId);
        Product GetProduct(int productId);
        IEnumerable<Product> GetAllProducts();
        IEnumerable<Product> GetAllProductsByCategory(int categoryId);
        IEnumerable<Category> GetAllCategory();
    }

 

And Service implementation :

 

    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        public ProductService(IProductRepository productService)
        {
            _productRepository = productService;
        }
        public void AddProduct(Product product)
        {
            _productRepository.Add(product);
        }
        public void RemoveProduct(Product productId)
        {
            _productRepository.Remove(productId);
        }
        public Product GetProduct(int productId)
        {
            var product = new Product { Id = productId };
            return product;
        }
        public IEnumerable<Product> GetAllProducts()
        {
            var products = _productRepository.GetAll();
            return products;
        }
        public IEnumerable<Product> GetAllProductsByCategory(int categoryId)
        {
            var products = _productRepository.GetAllProductsByCategoryQuery(categoryId);
            return products;
        }
        public IEnumerable<Category> GetAllCategory()
        {
            var categories = _productRepository.GetAllCategoriesQuery();
            return categories;
        }
    }
 

 and in Controllers folder create the ProductController with this definition

 

    public class ProductController : Controller
    {
      private readonly IProductService _productService;

        public ProductController(IProductService productService)
        {
            _productService = productService;
        }

        public ActionResult List()
        {
            var products = _productService.GetAllProducts();
            return View(products);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(Product product)
        {
            if (ModelState.IsValid)
            {
                _productService.AddProduct(product);
            }
            return View();
        }
  }

 

Which list action returns the list of products and by Add action, you can add a product, about the Dependency Resolver, add Ninject by Nuget :

 

Nuget

 

Then add this configuration class to your project

 

    public class NinjectConfig
    {
        private static IKernel _ninjectKernel;
        public class NinjectDependencyResolver : DefaultControllerFactory
        {
            public NinjectDependencyResolver()
            {
                _ninjectKernel = new StandardKernel();
                ConfigurDepndency();
            }
            protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
            {
                return controllerType == null ? null : (IController)_ninjectKernel.Get(controllerType);
            }
        }
        private static void ConfigurDepndency()
        {
            _ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
            _ninjectKernel.Bind<IProductService>().To<ProductService>();
        }
    }

 

And add this line of code to your global.asax in Application_Start()

 

 ControllerBuilder.Current.SetControllerFactory(new NinjectConfig.NinjectDependencyResolver()); 

 

 end!



Nhibernate vs Entity Framework

Entity framework and NHibernate are two famous ORM for developers. Both of them have been used in many projects and each of them has it's own cons and pros and common features as well. I'm gonna list some of them here. I personally like both of them and experienced in several projects. both Frameworks are used for processing relational data to domain-specific objects. Both NHibernate and the Entity Framework provide the capabilities required to implement an ORM using the Model First approach.

 

How do they work?

nHibernate: The ISessionFactory holds model and metadata that is tied to a particular database and to the settings that came from the Configuration object. Finally, you create instances of ISession from the ISessionFactory.

Entity Framework: the ObjectContext or DbContext holds the configuration, model and acts as the Unit of Work, holding references to all of the known entity instances. 

 

Migrations

Entity Framework: Built-in schema migration support since version 6 and supports seeding of the initial database

NHibernate: Supports only initial schema generation

 

Code First Mapping?

Both NHibernate and Entity Framework support the Code First Mapping feature.

 

Database Support?

NHibernate: SQL Server, SQL Server Compact, SQL Server Azure, Oracle, DB2, PostgreSQL, MySQL, Firebird, SQLite, Informix

Entity Framework: Entity framework only supports SQL Server (but by using some extensions you can use Oracle and MySQL too).

 

Caching?

Both of them support for the first level cache. NHibernate also supports for second level caching.

 

References:

I tried to list the features I've worked with and for the complete information you can see the following post:

https://weblogs.asp.net/ricardoperes/differences-between-nhibernate-and-entity-framework



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC