asp.netrepository-patternirepository

IRepository confusion on objects returned


I have some e-commerce code that I use often that uses Linq To SQL for saving orders to the database. I want to remove the tightly coupled Linq to SQL bit and pass in an IRepository instead but I am still a little confused on things.

Say I have a GetCustomer() method on my ICustomerRepository that returns a Customer object.

Do I need it to really return an ICustomer object that gets passed back from that method so if I switch from Linq To SQL to say SubSonic it's not a problem?

I believe I do, if that is the case is there a way in Linq To SQL to easily convert my Linq To SQL Customer object to my ICustomer object like SubSonics ExecuteSingle(Of ) method?


Solution

  • If you want your Customer class to be a plain object with no attachment to LINQ, then you will most likely need to write a mapper method to convert your LINQ-based Customer object to your plain Customer domain object. LINQ to SQL does not have such functionality built-in.

    I have begun to wrap my mapping methods in an extension method for readability, and it really helps to keep the Repository code simple. For instance, an example CustomerRepository method my look like:

    public Customer GetById(int id)
    {
       return dataContext.LINQCustomers.Where(c => c.Id == id)
                                       .Single()
                                       .ToDomainObject();
    }
    

    and the ToDomainObject() method is defined in an extension method like:

    public static class ObjectMapper
    {
        public static Customer ToDomainObject(this Customer linqObject)
        {
            var domainObject = null
            if (linqObject != null)
            {
                domainObject = new Customer
                {
                   Id = linqObject.Id,
                   FirstName = linqObject.FirstName,
                   LastName = linqObject.LastName
                }
            }
            return domainObject;
        }
    }
    

    or something similar. You can do the same to convert your domain object back to a LINQ object to pass back into your repository for persistence.