Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-factor my DAL code to a Domain Driven Design or more modern design (C# 3.5)?

The development is limited to Visual Studio 2010 (Client approved software). We need to access the data through stored procedures. I want to avoid making it too complex with an aggressive schedule. Most of the design I see involve EF and LINQ, Not sure how to design for procs?

I want to create a separate code library project (used Web UI):

Application.Domain
      -  Interact get/put stored procedures, entities

Application.Web
      - containing Web UI (JQuery, AJAX), WCF Service

Can anyone give me sample code on how to approach the Application.Domain?

Examples, I have read:

  • http://www.developer.com/net/dependency-injection-best-practices-in-an-n-tier-modular-application.html

    http://www.kenneth-truyers.net/2013/05/12/the-n-layer-myth-and-basic-dependency-injection/

DAL\AppDAL.cs:

public static IEnumerable<TasCriteria> GetTasCriterias()
    {
        using (var conn = new SqlConnection(_connectionString))
        {
            var com = new SqlCommand();
            com.Connection = conn;
            com.CommandType = CommandType.StoredProcedure;

            com.CommandText = "IVOOARINVENTORY_GET_TASCRITERIA";
            var adapt = new SqlDataAdapter();
            adapt.SelectCommand = com;
            var dataset = new DataSet();
            adapt.Fill(dataset);

            var types = (from c in dataset.Tables[0].AsEnumerable()
                         select new TasCriteria()
                         {
                              TasCriteriaId = Convert.ToInt32(c["TasCriteriaId"]),
                              TasCriteriaDesc= c["CriteriaDesc"].ToString()
                         }).ToList<TasCriteria>();

            return types;
        }

    }

Models\TasCriteria.cs:

public class TasCriteria
    {
        public int TasCriteriaId { get; set; }
        public string TasCriteriaDesc { get; set; }
    }

Service\Service.svc:

 [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "GET")]
        public List<TasCriteria> GetTasCriteriaLookup()
        {
            var tc = InventoryDAL.GetTasCriterias();
            return tc.ToList();
        }
like image 800
Chaka Avatar asked May 22 '14 17:05

Chaka


2 Answers

If you:

  • are running on a tight schedule
  • have most of the business logic already on the DB side via sprocs/views
  • have not worked with EF before

I suggest you take a look at the Microsoft Enterprise Library, especially the Data Application Block. It will simplifie ALL of your DAL functionality (without using any ORM framework) and it follows the dependency inversion principle with the help of Unity which is a dependency injection container from Microsoft.

Some helpfull Data Application Block concepts:

Output Mapper

An output mapper takes the result set returned from a database (in the form of rows and columns) and converts the data into a sequence of objects.

// Create and execute a sproc accessor that uses default parameter and output mappings 
var results = db.ExecuteSprocAccessor<Customer>("CustomerList", 2009, "WA");

Read the whole Retrieving Data as Objects topic.

Parameter Mapper

A parameter mapper takes the set of objects you want to pass to a query and converts each one into a DbParameter object.

// Use a custom parameter mapper and the default output mappings
IParameterMapper paramMapper = new YourCustomParameterMapper();
var results = db.ExecuteSprocAccessor<Customer>("Customer List", paramMapper, yourCustomParamsArray);

For Entity generation I would try to use this tool. It builds a POCO class from a resultset returned by a sproc. I have not tried this tool yet and maybe there are better alternatives but it is something to get you start with, so you dont have to do this by hand.

If you are using .NET 3.5 then you have to work with Enterprise Library 5.0.

I hope this will steer you in the right direction.

like image 133
Jernej Gorički Avatar answered Nov 03 '22 09:11

Jernej Gorički


first and foremost, make sure you abstract you DAL using dependency injection such as ninject or unity (or many others freely available). it is quite possible to have your DAL loosely coupled so that if you decide later on the EF (or any other ORM) is not the best course, changing it would no cost blood...

you do NOT want to have an AppDAL class with static methods to call the SP. at the very least add an interface and use injection, if only for the sake of unit testing.

whether you'll use EF or Nhibernate or any other ORM, that decision should be encapsulated in your DAL and not leak into other layers. the domain layer should use interfaces for repository classes from the DAL (and those contain references to the chosen ORM or data access classes).

these repositories will call the stored procedures and return your model classes (POCOs).

in one of my recent project we had this interface to provide basic CRUD operations:

public interface IRepository<T> where T : DomainEntity
{
    T Get(Int64 id);
    void SaveOrUpdate(T entity);
    void Delete(T entity);
    IQueryable<T> Find();
}

DomainEntity is a very simple class that all model clasess inherit. In the rare cases where we needed to use stored procedures I'd create an additional interface that provides a GetXXXEntity method (1 or more), that would do the actual call to the SP.

so, when I need to get an entity from the DB using it's Id, it would look like:

_diWrapper.GetRepository<Person>().Get(id);
_diWrapper.GetRepository<Order>().Get(id);

_diWrapper is my wrapper for the dependency injection container (ninject in this case). I used a wrapper so I could easily replace ninject with something else if needed.

in common cases where I need to use linq:

_diWrapper.GetRepository<Person>().Find().Where(q => q.Name == "Jack").ToList();

the important thing was that I could replace Nhibernate with anything else rather quickly.

I strongly recommend you look at Fluent NHibernate, as it provides a simple solution that does not require much coding.

EDIT: here's an example of the repository class implementing the IRepository interface:

public class NhibernateRepository<T> : IRepository<T> where T : DomainEntity, new()
{
    private ISession _session;

    public NhibernateRepository()
    {
        _session = BaseNHibernateHelper<NHibernateHelper>.GetCurrentSession();
    }

    public T Get(Int64 id)
    {
        return _session.Get<T>(id);
    }

    public void SaveOrUpdate(T entity)
    {
        _session.SaveOrUpdate(entity);
    }

    public void Delete(T entity)
    {
        _session.Delete(entity);
    }

    public IQueryable<T> Find() 
    {
        return _session.Query<T>();
    }
}

note that in the constructor I use another nhibernate helper I created that wraps the session factory. this is where I have a dependency on nhibernate.

if I ever wanted to replace NH with another ORM, I would need to modify only the repository class (and the underlying supporting classes), you can see that NH does not leak outside the Repository class and no one that uses it are aware of the usage of NH.

like image 45
Ami Avatar answered Nov 03 '22 09:11

Ami