Posts tagged ‘Entity Framework 4.0’

At long last (On a couple of levels I have to add)!

First and foremost – after a long absence from blogging due to a life-changing event (i.e. recent addition to the family) I have managed to write up an article that has been on my mind since June last year! Secondly, because I finally managed to get the example to work – after months of on and off attempts I had been blocked by a very silly and obvious issue (more later) and this evening I managed to concentrate and see it through.

So what’s the big deal?

My desire was to write a blog explaining the beauty of using POCO from EF 4.0 all the way up through WCF to a client application. I had naively assumed that it would be a straightforward case of building the EFDM, creating my POCO classes, create the appropriate Context Interface (see my earlier blog article on creating an appropriate Context Interface) and then write the WCF service to use the EFDM and expose the same POCO classes to the client – how naïve!

The issue actually came up when I tried to pass the EF “filled” POCO classes back through the WCF service. Bang! I got stumped with the following exception:

System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Although I had the WCF Tracing enabled; I couldn’t for the life of me figure out what it was. Finally after digging through fresh traces I read carefully what the buried exception was:

There was an error while trying to serialize parameter http://tempuri.org/:GetDiverResult. The InnerException message was 'Object graph for type 'DiveLogger.Base.DataContracts.DiveProfile' contains cycles and cannot be serialized if reference tracking is disabled.'.  Please see InnerException for more details.

Of course! How silly of me! It was the fact that the navigation properties of my entities were actually causing cyclic references. Now there was a couple of ways I could do this.

  1. Scrutinize my navigation properties and make sure that the return reference properties were made private (this way the XML Serialization of WCF would overlook it as they would be POCO (i.e. no DataContract attributes here!) – it does work as I tried it out for a laugh.
  2. Utilize the blogged “Cyclic References Aware Contract Behavior” derived from IContractBehavior example. This would allow me to pass my POCO class through un-changed and not cause an exception (that would shutdown my service connection unexpectedly).

In the attached code example I have used the second option as I want to try and demonstrate how we can go from Data Model through EF context to the client via a WCF Service, without decorating our class with any special attributes or referencing any EF or Serialization classes – i.e. real to goodness POCO!

As my regular readers will recognize by now that my reason for being so excited about this (apart from the ability to inject interfaces and have my separation of concerns) is for the all important Unit Tests – after all what fun would it be?

The idea of this exercise was to show that with .NET 4.0 we can now release our bonds to specific assemblies / classes and have truly lightweight classes. Consider how pre-4.0 would have been done:

POCO through technology stack

Each layer would have involved some form of transformation from one type to another simply to avoid issues with the associated technology stack.

Consider the “new” way with .NET 4.0:

POCO through technology stack

Now we don’t have to do any transformation from one type to another because the same type is used all the way up the technology stack without any issues (except for the one described earlier).

So how was it done?

The following steps will guide you through the process:

1. Define our POCO classes according to our Data Model:

[POCO classes]

POCO Definition

[Data Model]

EF Data Model

2. Remove the Custom Tool from the DataMapping properties
(so that we can use POCO):

EFDM Custom Tool

Effect of removing EFDM Custom Tool

3. Define the Context Interface that will become the injection point in future references to the DAL:

    public interface IDiveLoggerContext
    {
        IObjectSet AccessTypes { get; }
        IObjectSet CertificationTypes { get; }
        IObjectSet DiveProfiles { get; }
        IObjectSet Divers { get; }
        IObjectSet DiveSites { get; }
        IObjectSet SurfaceTypes { get; }
        IObjectSet WaterBodyTypes { get; }
    }

And implement it

Implement Context Interface

4. In a WCF project define the Service Interface (we will not decorate the DataContracts as they are POCO):

namespace DiveLogger.Service
{
    [ServiceContract]
    public interface ILoggerService
    {
        [OperationContract]
        Diver GetDiver(int id);
    }
}
5. Create the CyclicReferencesAwareContractBehavior, CyclicReferencesAwareAttribute and ApplyCyclicDataContractSerializerOperationBehavior classes as described in Chabsters blog (WCF Cyclic references support). Obviously if there are no cyclic references in any of our entities, then chances are you will not need to put in this workaround for WCF 4.0.

Cyclic Reference Treatment Classes

And use it on the Service contract

Use CyclicReferencesAware attribute

Now the XmlSerialization can handle those pesky cyclic reference Navigation Properties and our WCF Service will work.

6. Utilize the Context Interface we created earlier to separate the DAL from the Service:

    public class LoggerService : ILoggerService
    {
        private IDiveLoggerContext m_context;

        public LoggerService()
        {
            Initialize(null);
        }

        internal LoggerService(IDiveLoggerContext i_context)
        {
            Initialize(i_context);
        }

        private void Initialize(IDiveLoggerContext i_context)
        {
            m_context = i_context ?? new DiveLoggerContext(UtilityFunctions.BuildAdoConnectionString(null));
        }

        public Diver GetDiver(int id)
        {
            if (id < 1 || id > 999)
                throw new ArgumentOutOfRangeException("Diver ID needs to be between 1 and 999", "id");

            IQueryable query = from diver in m_context.Divers
                                      .Include("CertificationTypes")
                                      .Include("DiveProfiles")
                                      .Include("DiveProfiles.DiveSite")
                                      .Include("DiveProfiles.WaterBodyType")
                                      .Include("DiveProfiles.AccessType")
                                      .Include("DiveProfiles.SurfaceType")
                                      where diver.Id == id
                                      select diver;
            Diver retVal = query.ToList().SingleOrDefault();
            return retVal;
        }
    }
7. In our Unit Test we can mock out the Context Interface instead of generating an actual instance:

    [TestMethod]
    public void TestGetSingleDiver()
    {
        // - ARRANGE -
        // Create the stub instance
        IDiveLoggerContext context = MockRepository.GenerateStub();

        // define/create dummy data
        int id = 500;
        string firstName = "Sherlock";
        string lastName = "Holmes";
        string title = "Mr.";
        IObjectSet divers = TestHelper.CreateDivers(id, firstName, lastName).AsObjectSet();

        // declare instance that we want to "retrieve"
        Diver individual;

        // Explicitly state how the stubs should behave
        context.Stub(stub => stub.Divers).Return(divers);

        // Create a real instance of the Servcie that we want to put under test, injecting the dependency in the constructor
        LoggerService service = new LoggerService(context);

        // - ACT -
        individual = service.GetDiver(id);
        // - ASSERT -
        // Make absoultely sure that the expected excption type was thrown
        Assert.IsNotNull(individual);
        // Make sure that the method was NOT called.
        context.AssertWasCalled(stub => { var temp = stub.Divers; });
    }

This will mean that we can get more realistic code-coverage on our Service:

Code Coverage

The following zip file contains all of the classes and code mentioned in the steps outlined previously:

Divelogger.zip

  • Share/Bookmark

Visual Studio 2010 - Beta 2

Whilst preparing for my Entity Framework 4.0 and Unit Testing presentation at the recent New England Code Camp, I came across an issue with my code that I couldn’t entirely understand. Picture the scenario:

In Visual Studio 2008 utilizing EF 1.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [store the Manager.cs file in a common area and create a Link to it from the project].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include() [Did I say I hate "magic strings"?]
    [store the ObjectQueryExtension.cs file in a common area and create a Link to it from the project]
  • Create a simple Console app to call the methods on the Manager class
    [store the Program.cs file in a common area and create a Link to it from the project].

Visual Studio 2008

In Visual Studio 2010 Beta 2 utilizing EF 4.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [create a Link to the Manager.cs file from the project in a common area].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include()
    [create a Link to the ObjectQueryExtension.cs file in the common area from the project]
  • Create a simple Console app to call the methods on the Manager class
    [create a Link to the Program.cs file in the common area from the project].

Visual Studio 2010 - Beta 2

As you will see, the only difference between the two solutions is the actual EntityFramework context definition; one utilizes EF 1.0 and the other EF 4.0.

Compile and execute both and it works perfectly, same Program.cs code for both (making the Console Application); same Manager.cs and ObjectQueryExtension.cs code for both (making the RepositoryManager assembly).

Now the fun starts. I then worked my way back to using Dependency Injection and created the unit test methods based on the VS 2010 project described above. When the compiler attempts to compile the following section of code:


IQueryable<Person> query = context.PersonSet
                               .Include(p => p.PersonalDetail)
                               .Include("FavoriteBeers.Beer")
                               .Include(p => p.Customer.Include<Customer, CustomerType>(c => c.CustomerType))
                               .Include(p => p.Addresses);

The following compile error was the result of the attempted compilation against the preceding code:


Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,53): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,58): error CS0311: The type 'EFWorkshop.Poco.Base.Entities.Customer' cannot be used as type parameter 'TSource' in the generic type or method 'EFWorkshop.Ef.Repository.ObjectQueryExtension.Include<TSource,TPropType>(TSource, System.Linq.Expressions.Expression<System.Func<TSource,TPropType>>)'. There is no implicit reference conversion from 'EFWorkshop.Poco.Base.Entities.Customer' to 'System.Data.Objects.DataClasses.IEntityWithRelationships'.
Ef4.0AndEf1.0\Common\ObjectQueryExtension.cs(118,33): (Related location)
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,60): error CS1061: 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' does not contain a definition for 'Customer' and no extension method 'Customer' accepting a first argument of type 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' could be found (are you missing a using directive or an assembly reference?)

However, the following “magic string” laden Includes compile and execute fine:


IQueryable<Person> query = _context.People
    .Include("FavoriteBeers.Beer")
    .Include("PersonalDetail")
    .Include("Customer.CustomerType")
    .Include("Addresses");

Therefore it would seem that the non POCO based classes permit us having the Lambda expression based includes as described earlier; however the moment that POCO is introduced that style of Include is no longer viable – or is it?

  • Share/Bookmark

Wow – June 24th was the last entry! First of all I need to apologize for my bad blogging; I have no other excuse except for the volume of work AT work. Sure I could have re-prioritized and it may have made a difference, but I don’t think my employer would have been very pleased.

So, New England Code Camp, Microsoft Offices, Waltham, MA – full information can be found at http://www.thedevcommunity.org/Events/PresentationList.aspx?id=13. Today I am giving two presentations:

Using Entity Framework’s New POCO Features: Part 2 (Unit Testing)

Level: Intermediate

Starts: Oct 17 2009 2:50 PM

Ends: Sep 17 2009 4:05 PM

Room: MPR A

Speaker: James Phillips

In many cases Unit Testing is considered a chore rather than another development task and often ends up being the last task in a development cycle. More often than not, the sheer work involved in preparing unit tests for existing code can lead to the production of Integration Tests rather than true Unit Tests. Where a unit of code that is under test relies on an external resource, such as a Database or Configuration file, the dependency can lead to testing of the underlying mechanism as well as the unit being tested. This was especially true with Entity Framework 1.0 shipped with .NET Framework 3.5 Service Pack 1. With the advent of .NET Framework 4.0, the Entity Framework has advanced in favor of better Unit Testing with the use of POCO and the ability to create interfaces based on IObjectSet. This presentation will cover the examples that can lead to true Unit Testing as opposed to Integration Testing and provide valuable feedback metrics such as code coverage and automated build time reporting of results.

SCRUM and TFS

Level: Introductory

Starts: Oct 17 2009 4:10 PM

Ends: Sep 17 2009 5:25 PM

Room: Rhode Island

Speaker: James Phillips

SCRUM has grown in popularity and acceptance by many companies over the world with numbers of registered SCRUM Masters reaching 51,955 (11 March 2009 – Jeff Sutherland). Although SCRUM does not stipulate what tools to use to produce the necessary artifacts, Microsoft Team Foundation System provides a number of features via TFS Explorer that facilitate capturing the artifacts of SCRUM and is a useful tool for any SCRUM Master, Team and Product Owner. This presentation will highlight the SCRUM framework and show you practical use of TFS and other tools that facilitate the ceremonies and artifacts of SCRUM.

The slides and code are available for download here:

SCRUM_And_TFS.zip

EF_POCO_And_UnitTesting_slides.zip”

EF_POCO_And_UnitTesting_code.zip

EF_POCO_And_UnitTesting.zip

  • Share/Bookmark

After publishing the blog article on Mocking in EF 2.0, Diego Vega (Microsoft Program Manager Entity Framework and LINQ to SQL Product Teams in Redmond) pointed out that the following code snippet is quite inefficient:


    var customers = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus);
    if (customers.Count() == 1)
    {
        o_customer = customers.Single<Customer>();
    }
    else
    {
        o_customer = null;
    }

It turns out that even though the expression does not change between the call to customers.Count() and customers.Single<Customer>(), they will actually cause two calls to the Database. I had mistakenly assumed that the result would be cached as there was no change to the “query”.

By using the SingleOrDefault<T>() function that is now available in EF 2.0 (through IQueryable<T>) we actually save on the round trip.


    o_customer = (from cus in _context.Customers
                    where cus.CustomerID == i_customerId
                    select cus).SingleOrDefault<Customer>();

Something to bear in mind when working with IQueryable<T>.

a2dbm5vn79

  • Share/Bookmark

Finally! I’ve been itching to get into the latest incarnation of the EF for a while now and finally I had the opportunity to take it around the block (kick the tires and generally rough it up). My main interest in EF 2.0 was the supposed support for Unit Testing and the improvements on using POCO to map to the Data Model.

I have to admit, although I liked EF 1.0 when I first started using it, one of my biggest bug bears was the fact that you had to “disconnect” your entities before you could really work with them outside the context (no pun intended) of the Entity Framework. I was also quite miffed when I discovered there was no easy way to mock the underlying data layer so I ended up with code like this:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        m_customerRepository.Load(i_customerId, out o_customer);

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

In this case, m_customerRepository is the injected ICustomerRepository instance. When we look at the implementation of the actual data layer class (which does not get tested by the Unit Test, we find that inside the Load method we have the following:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out BaseCustomer o_customer)
    {
        Customer customer = (CustomerSet.Where(cust => !string.IsNullOrEmpty(cust.CustomerID) &&
                                                       cust.CustomerID == i_customerId)).First();
        if (customer != null)
        {
            o_customer = new BaseCustomer()
                             {
                                 Address = customer.Address,
                                 City = customer.City,
                                 CompanyName = customer.CompanyName,
                                 ContactName = customer.ContactName,
                                 ContactTitle = customer.ContactTitle,
                                 Country = customer.Country,
                                 CustomerID = customer.CustomerID,
                                 Fax = customer.Fax,
                                 Phone = customer.Phone,
                                 PostalCode = customer.PostalCode,
                                 Region = customer.Region
                             };
        }
        else
        {
            o_customer = null;
        }
    }

Not the best way of doing things, that is for sure! In fact it is downright ugly (IMHO). So when I heard that there were improvements to the EF for .NET 4.0, especially in the area of Unit Testing I was curious to say the least. As I delved in deeper I started finding more and more things that made it more attractive to my style of development. For example one of the beauties of EF 2.0 is the fact that you can remove the CustomTool that generates the entity classes that are bound to the data model (through the edmx file). When you do this, you effectively get rid of the code generation for the EF instance that you have loaded in your project. There are some excellent examples (and walkthroughs available) from the ADO.NET Team blog:

POCO in Entity Framework : Part 1 – The Experience (excellent walkthrough on removing the CustomTool)

POCO in Entity Framework : Part 2 – Complex Types, Deferred Loading and Explicit Loading

POCO in Entity Framework : Part 3 – Change Tracking with POCO

So now what? Great! So now I can use my POCO to update the Data Model. But I still hadn’t found out how to do true unit testing with DI and mocking? I was quite flummoxed until I realized (with a helpful pointer from a friend at Microsoft – thanks Jason) that the answer was staring me in the face:

“Can’t you create a mock class that derives from IObjectSet instance yourself, or is there a problem doing that?”

Well yes, I did have a problem with that – it meant that I would have to write more code. I was naively hoping to have something like:


List<Customer> cusList = TestHelper.CreateCustomerList();
IObjectSet<Customer> context = cusList.AsObjectSet();

So I was being lazy… I guess that, with each version of .NET, I had become more and more accustomed to so much being done for me that stumbling across something as “simple” as creating an AsObjectSet() function that was not available was bit of a shock. More so when you look at what IS available on a List<entity> method / property list.

At first I contented myself with just doing what was obvious – create a mock class that inherited from IObjectSet<Customer>, before I realized (with another push from Jason) that I could make it more generic and have a MockObjectSet<T> class:


    internal class MockObjectSet<T> : IObjectSet<T>
        where T : class
    {
        public MockObjectSet(List<T> entityList)
        {
            if (entityList == null)
            {
                throw new ArgumentNullException("entityList");
            }
            else
            {
                _repository = entityList.ToList();
            }
        }

        IList<T> _repository;

        #region IObjectSet<T> Members

        public void AddObject(T entity)
        {
            _repository.Add(entity);
        }

        public void Attach(T entity)
        {
            this.AddObject(entity);
        }

        public void DeleteObject(T entity)
        {
            _repository.Remove(entity);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _repository.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _repository.GetEnumerator();
        }

        #endregion

        #region IQueryable Members

        public Type ElementType
        {
            get { return typeof(T); }
        }

        public System.Linq.Expressions.Expression Expression
        {
            get { return _repository.AsQueryable<T>().Expression; }
        }

        public IQueryProvider Provider
        {
            get { return _repository.AsQueryable<T>().Provider; }
        }

        #endregion
    }

It is important to note here that the TestHelper.CreateCustomerList() function has several overrides and returns a List<Customer> filled with dummy data.

After playing around a bit I realized that I could actually just create an Extension Method that would create an instance of the mock CustomerSet and therefore I could call it from within my Unit Test code. The Extension Method looks like this:


    public static class ObjectSetExtension
    {
        public static IObjectSet<T> AsObjectSet<T>(this List<T> entities) where T : class
        {
            return new MockObjectSet<T>(entities);
        }
    }

Now if we revisit the unit test code, we get the following:


        [TestMethod]
        public void TestLoadValidCustomerContactNameWithSurname()
        {
            // Arrange
            // Create the stub instance
            INorthwindContext context = MockRepository.GenerateStub<INorthwindContext>();
            // Create the dummy data
            const string customerId = "555";
            const string contactName = "James Person";
            IObjectSet<Customer> customers = TestHelper.CreateCustomerList(contactName, customerId).AsObjectSet();

            // declare the dummy instance we are going to use
            Customer loadedCustomer;

            // Explicitly state how the stubs should behave
            context.Stub(stub => stub.Customers).Return(customers);

            // Create a real instance of the CustomerManager that we want to put under test
            Managers.CustomerManager manager = new Managers.CustomerManager(context);

            // Act
            manager.Load(customerId, out loadedCustomer);

            // Assert
            context.AssertWasCalled(stub => { var temp = stub.Customers; });
            // Check the expected nature of the dummy intance
            Assert.IsNotNull(loadedCustomer);
            Assert.IsNotNull(loadedCustomer.ContactName);
            Assert.IsTrue(loadedCustomer.ContactName == "James PERSON");
        }

If we compare the two managers again (the manager that I had created in a previous blog posting depended on EF 1.0), we will see that the EF 2.0 instance actually contains lambda expressions to do the queries.

EF 1.0:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        m_customerRepository.Load(i_customerId, out o_customer);

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

EF 2.0:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        var customers = (from cus in _context.Customers
                         where cus.CustomerID == i_customerId
                         select cus);
        if (customers.Count() == 1)
        {
            o_customer = customers.Single<Customer>();
        }
        else
        {
            o_customer = null;
        }

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

In the second code, snippet, because I am calling straight to an instance of IObjectSet<Customer>, it could either be my mocked one or the actual Entity Framework instance, which looks like this (thanks to POCO binding):


    public class NorthwindContext : ObjectContext, INorthwindContext
    {

        public NorthwindContext()
            : base("name=NorthwindEntities", "NorthwindEntities")
        {
        }

        private ObjectSet<Order> _orders;
        private ObjectSet<Employee> _employees;
        private ObjectSet<Customer> _customers;

        #region INorthwindContext Members

        IObjectSet<Employee> INorthwindContext.Employees
        {
            get { return _employees ?? (_employees = CreateObjectSet<Employee>()); }
        }

        IObjectSet<Customer> INorthwindContext.Customers
        {
            get { return _customers ?? (_customers = CreateObjectSet<Customer>()); }
        }

        IObjectSet<Order> INorthwindContext.Orders
        {
            get { return _orders ?? (_orders = CreateObjectSet<Order>()); }
        }

        #endregion
    }

This means that when I run my code coverage for the EF 2.0 version, I will be hitting the true boundary between the entity and the model, thanks to a combination of POCO and the separation of concerns brought about by IObjectSet.

Ok, so there’s no kitchen sink – what would you do with it if there was?

  • Share/Bookmark