Archives

Archives / 2010 / July
  • Integrated StructureMap container for the MvcServiceLocator in ASP.NET MVC 3

    ASP.NET MVC 3 just released a few days ago. In this release, Microsoft team published some features very cool. I really love that, because we shall code easier. See release note for more information. And in this post, I would like to explore about MvcServiceLocator, one of features very interesting in this release. So why I want to know about that? Because in the past project in codeplex http://nma.codeplex.com, I used to CommonServiceLocator from Microsoft, and I must to customize it for integrated with StructureMap. Now, I don’t need making like that, because ASP.NET MVC team has already integrated it into core of ASP.NET MVC 3. That enough to talking, I only care about coding because I don’t want to talk more but not practice.

  • The short example about Entity Framework 4 CTP4 - Part 3

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4

    • Come with Entity Framework extensions

    Go to http://code.msdn.microsoft.com/EFExtensions/Release/ProjectReleases.aspx?ReleaseId=3624. And getting a source code of Entity Framework extensions, you must build it and get the dll with named EFExtensions.dll

    • Talk about Materializer and DbCommand

    We need a Materializer for build a static function that mapping a model contract with the result return from the store procedure. And we need the DbCommand for executing a store procedure. That is all things I knew about it. For more information, go to http://blogs.msdn.com/b/meek/archive/2008/03/26/ado-entity-framework-stored-procedure-customization.aspx. I think a expert at here will explain easily understanding than me. The theory is enough; I should focus on my work.

    • Build Contract Model for storing result that return from Store-Proc

    I must build the Contract Model for mapping result that invoke the store procedure

    public class SumarizeCategoriesAndNews
        {
            /// <summary>
            /// Gets or sets the category id.
            /// </summary>
            /// <value>The category id.</value>
            public int CategoryId { getset; }

            /// <summary>
            /// Gets or sets the name of the category.
            /// </summary>
            /// <value>The name of the category.</value>
            public string CategoryName { getset; }

            /// <summary>
            /// Gets or sets the category created date.
            /// </summary>
            /// <value>The category created date.</value>
            public DateTime CategoryCreatedDate { getset; }

            /// <summary>
            /// Gets or sets a value indicating whether [category is delete].
            /// </summary>
            /// <value><c>true</c> if [category is delete]; otherwise, <c>false</c>.</value>
            public bool CategoryIsDelete { getset; }

            /// <summary>
            /// Gets or sets the new id.
            /// </summary>
            /// <value>The new id.</value>
            public int NewId { getset; }

            /// <summary>
            /// Gets or sets the news title.
            /// </summary>
            /// <value>The news title.</value>
            public string NewsTitle { getset; }

            /// <summary>
            /// Gets or sets the content of the news.
            /// </summary>
            /// <value>The content of the news.</value>
            public string NewsContent { getset; }

            /// <summary>
            /// Gets or sets the news created date.
            /// </summary>
            /// <value>The news created date.</value>
            public DateTime NewsCreatedDate { getset; }

            /// <summary>
            /// Gets or sets a value indicating whether [news is delete].
            /// </summary>
            /// <value><c>true</c> if [news is delete]; otherwise, <c>false</c>.</value>
            public bool NewsIsDelete { getset; }
        }
    • Re-code the DbContext for mapping store procedure

    Next, I built the CSPDbContext partial class with named CSPDbContext.StoreProc and its code here:

        public partial class CSPDbContext
        {        
            private static readonly Materializer<SumarizeCategoriesAndNews> s_sumarizeCatAndNewsMaterializer = new Materializer<SumarizeCategoriesAndNews>(r =>
                new SumarizeCategoriesAndNews
                {
                    CategoryId = r.Field<int>("CategoryId"),
                    CategoryName = r.Field<string>("CategoryName"),
                    CategoryCreatedDate = r.Field<DateTime>("CategoryCreatedDate"),
                    CategoryIsDelete = r.Field<bool>("CategoryIsDelete"),
                    NewId = r.Field<int>("NewId"),
                    NewsTitle = r.Field<string>("NewsTitle"),
                    NewsContent = r.Field<string>("NewsContent"),
                    NewsCreatedDate = r.Field<DateTime>("NewsCreatedDate"),
                    NewsIsDelete = r.Field<bool>("NewsIsDelete"),
                });

            /// <summary>
            /// Gets the sumarize category and news.
            /// </summary>
            /// <returns></returns>
            public SumarizeCategoriesAndNews GetSumarizeCategoryAndNews()
            {
                // The CreateStoreCommand utility method simplified creation
                DbCommand command = this.ObjectContext.CreateStoreCommand(
                    "SumarizeCategoryAndNews",
                    CommandType.StoredProcedure,
                    null);
                SumarizeCategoriesAndNews catAndNews = s_sumarizeCatAndNewsMaterializer
                    .Materialize(command)   // Returns typed results given a DB command.
                    .SingleOrDefault();     // We expect at most a single match for this stored procedure.

                return catAndNews;
            }
        }

    As you see, I invoked the store-proc with named [SumarizeCategoryAndNews]. I think it is clear with anyone that read this code.

    And the Repository, we only need called it as:

            public SumarizeCategoriesAndNews GetSumarizeCategoriesAndNews()
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                return temp.GetSumarizeCategoryAndNews();
            }

     

    Finally I do unit testing for this function:

             [TestMethod()]
            public void GetSumarizeCategoriesAndNewsTesting()
            {
                var result = CategoryRepository.GetSumarizeCategoriesAndNews();

                Assert.IsNotNull(result);
                Assert.AreEqual(result.CategoryName, "test");
                Assert.AreEqual(result.CategoryIsDelete, false);
            }
    Notes:
    • You must run the Databasescript.sql to created the store-proc after you created successful the database schema
    • You must set the command 
      Database.SetInitializer<CSPDbContext>(newRecreateDatabaseIfModelChanges<CSPDbContext>());
      //Database.SetInitializer<CSPDbContext>(new DontTouchMyDatabase<CSPDbContext>());
      at Testing base class for created new database schema
    More developing:
    • Intergrated with IoC container (Unity 2.0, Structure Map, MEF,..) 
    • Do more Unit Testing
    Read further:
    • Data Annotation on EF4 CTP4
    • WCF ADO.NET Data Service based on EF4 CTP4 

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    Part 2: Repository and Unit of Work on Entity Framework 4

  • The short example about Entity Framework 4 CTP4 - Part 2

    Part 2: Repository and Unit of Work on Entity Framework 4

    • Create the repository for persistence ignorance

    Up to now, I very love the Persistence Ignorance. So what is it? I remembered that I usually built the Data Access Layer for access Database in the past. That is make your layer is coupling with the Database. So it is not good if you change database, change something else. So what do you think if we don’t need to know about it? Just tell the class that “I want to make something, and don’t care what happen in the behind scene.” It’s really good, and that is a place where Repository pattern jumps into. For more information, go to http://martinfowler.com/eaaCatalog/repository.html. I don’t want to speak more about it. Now we shall continue on my example. The first thing, we must to build is a IRepository interface for making a contract.

        public interface IRepository<T> where T : IEntity
        {
        }

    IRepository is constraint on T generic type and must be an IEntity. Now I want to separate with 2 Repositories that do specific jobs. At here, I divided 2 Repositories with 2 contracts are: ICommandRepository and IQueryRepository. ICommandRepository contains all actions about CRUD, and IQueryRepository contains all actions about query data. That is it.

        public interface ICommandRepository<T> : IRepository<T> where T : IEntity
        {
            /// <summary>
            /// Gets the by id.
            /// </summary>
            /// <param name="id">The id.</param>
            /// <returns></returns>
            T GetById(int id);

            /// <summary>
            /// Adds the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            /// <returns></returns>
            T Add(T entity);

            /// <summary>
            /// Updates the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            void Update(T entity);

            /// <summary>
            /// Deletes the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            void Delete(T entity);

            /// <summary>
            /// Deletes the specified id.
            /// </summary>
            /// <param name="id">The id.</param>
            void Delete(int id);

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            IUnitOfWork UnitOfWork();
        }

    And,

        public interface IQueryRepository<T> : IRepository<T> where T : IEntity
        {
            /// <summary>
            /// Gets all.
            /// </summary>
            /// <returns></returns>
            IEnumerable<T> GetAll();

            /// <summary>
            /// Gets the specified where.
            /// </summary>
            /// <param name="where">The where.</param>
            /// <returns></returns>
            IEnumerable<T> Get(Func<T, bool> where);
        }

    I also have a base Repository for re-use all things that you think it can shared for all Repository used.

        public abstract class BaseRepository<T> : IDisposable
        {
            private DbContext _dbContext;

            /// <summary>
            /// Initializes a new instance of the <see cref="BaseRepository&lt;T&gt;"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public BaseRepository(IDatabaseFactory databaseFactory)
            {
                Contract.Assert(databaseFactory != null"DatabaseFactory is null");

                DatabaseFactory = databaseFactory;
            }

            /// <summary>
            /// Gets or sets the database factory.
            /// </summary>
            /// <value>The database factory.</value>
            protected IDatabaseFactory DatabaseFactory
            {
                get;
                private set;
            }

            /// <summary>
            /// Gets the db context.
            /// </summary>
            /// <value>The db context.</value>
            protected DbContext DbContext
            {
                [DebuggerStepThrough]
                get
                {
                    return _dbContext ?? (_dbContext = DatabaseFactory.Get());
                }
            }

            /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            public void Dispose()
            {
                if (DbContext != null)
                    GC.SuppressFinalize(DbContext);

                if (DatabaseFactory != null)
                    GC.SuppressFinalize(DatabaseFactory);
            }
        }
    Now we can implement the CategoryRepository as below:
        public interface ICategoryRepository : ICommandRepository<Category>, IQueryRepository<Category>
        {
        }
        public class CategoryRepository : BaseRepository<Category>, ICategoryRepository
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CategoryRepository"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public CategoryRepository(IDatabaseFactory databaseFactory)
                : base(databaseFactory)
            {
            }

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            public IUnitOfWork UnitOfWork()
            {
                return DbContext as CSPDbContext;
            }

            /// <summary>
            /// Gets the by id.
            /// </summary>
            /// <param name="id">The id.</param>
            /// <returns></returns>
            public Category GetById(int id)
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                return (temp).Categories.Where<Category>(x => x.Id == id).FirstOrDefault<Category>();
            }

            /// <summary>
            /// Adds the specified entity.
            /// </summary>
            /// <param name="entity">The entity.</param>
            /// <returns></returns>
            public Category Add(Category entity)
            {
                Contract.Assert(DbContext != null"DbContext is null");

                var temp = DbContext as CSPDbContext;
                temp.Categories.Add(entity);

                return entity;
            }

            ...


        }
    • Unit of Work on EF4 

    This is a hard pattern in EF4, so I will don’t explain about it. I just gave you a reference to read it, and I also implemented according to this link

    http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

    This is my code:

        public interface IUnitOfWork
        {
            /// <summary>
            /// Saves this instance.
            /// </summary>
            void Save();
        }
     
        public partial class CSPDbContext : DbContextIUnitOfWork
        {
            ...
            /// <summary>
            /// Saves this instance.
            /// </summary>
            public void Save()
            {
                SaveChanges();
            }
        }

    I gave the CSPDbContext implementing the IUnitOfWork contract, and

    public class CategoryRepository : BaseRepository<Category>, ICategoryRepository
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CategoryRepository"/> class.
            /// </summary>
            /// <param name="databaseFactory">The database factory.</param>
            public CategoryRepository(IDatabaseFactory databaseFactory)
                : base(databaseFactory)
            {
            }

            /// <summary>
            /// Units the of work.
            /// </summary>
            /// <returns></returns>
            public IUnitOfWork UnitOfWork()
            {
                return DbContext as CSPDbContext;
            }
            ...
        }

    Now I do unit testing for CategoryRepository as:

            [TestMethod()]
            public void GetAllTesting()
            {
                var result = CategoryRepository.GetAll();
                Assert.IsNotNull(result);
            }
            [TestMethod()]
          public void AddCategoryTesting()
            {
                var entity = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test"
                });

                Assert.IsNotNull(entity);
                Assert.AreEqual(entity.Name, "test");
                Assert.AreEqual(entity.IsDelete, false);
            }

    Unit testing for UnitOfWork:

            [TestMethod()]
            public void UnitOfWorkTesting()
            {
                var uow = CategoryRepository.UnitOfWork();

                var entity1 = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test3",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test3"
                });

                var entity2 = CategoryRepository.Add(new CallStoreProc.Data.Entity.Category()
                {
                    Name = "test4",
                    IsDelete = false,
                    CreatedDate = DateTime.Now,
                    Description = "test4"
                });

                uow.Save();
            }
     

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4

  • The short example about Entity Framework 4 CTP4 - Part 1

    A few days ago, I have read an article from Mr. huyrua, the person that I have a deep respect. The code that he implemented is very good to me. And I have an idea for implementing something in Entity Framework 4. You can go to http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern and see the best solution on multiple ObjectContext, according to me; it is a best solution in Entity Framework.

    Microsoft just released Microsoft ADO.NET Entity Framework Feature Community Technology Preview 4 in 2010/07/13. And I really interested in it. In this new release, I found many features very cool. And now they support Convention over Configuration on DbContext class, instead of ObjectContext class in old version. So I want to explore it in this post. Because this post maybe long, so I divided into 3 parts:

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    • Prepare tool for stepping up EF 4

    • The first introduce about my approaches

    • Build the heart of EF4 (Entity)

    • Mapping entity with database table

    • Build your DbContext, DbContext factory

    Part 2: Repository and Unit of Work on Entity Framework 4

    • Create the repository for persistence ignorance

    • Unit of Work on EF4

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4

    • Come with Entity Framework extensions

    • Talk about Materializer and DbCommand

    • Build Contract Model for storing result that return from store procedure

    • Re-code the DbContext for mapping store procedure

    Part 1: Step up ADO.NET Entity Framework 4 CTP4

    • Prepare tool for stepping up EF 4

    If you want to use EF 4 CTP4, you must download it at http://www.microsoft.com/downloads/details.aspx?FamilyID=4e094902-aeff-4ee2-a12d-5881d4b0dd3e&displayLang=en

    After installed it, you shall have enough tool for run EF 4 CTP, and the important dll that you should focus is Microsoft.Data.Entity.CTP.dll, product version is 4.0.30202.0. I usually copy it to one folder in my solution (at here I create a folder with named [References] and put that dll into this folder). Later we must reference it in our solution.

    • The first introduce about my approaches

    Why did I choose EF4 CTP4? It is simple that EF4 CTP4 is code-first approach, so I can control more things in EF4. I can create model, mapping, db context… All things in code-first are code, I love it. I always resist the problem must read the auto-generated code from the Designer tool.

    In old days, we usually use the ObjectContext for making the context for our solution. So you must create the EntityConnection instance for injecting it into the ObjectContext. It must be a concrete instance. Now in the CTP4 version, ADO.NET EF4 team introduced the new class with named DbContext, this class using Convention over Configuration for choosing the Database Provider. If you do not specific the connection name, DbContext will create the Database for you, and else DbContext will use the specific connection name that you pass into the ctor of DbContext class.

    In an example in this post, I used DbContext for making Database Context.

    • Build the heart of EF4 (Entity)

    In the new methodology, we do not care about creating database schema. We only focus on model and trivial model become the heart of modern software. In this example, I also focus on model and use the model to generate the database schema.

    For easy to understanding, I will describe something about my example. I have the category that manages the news. Certainly, one category must have much news. And I keep this example as simple as possible.

    After analyze, we have 2 tables, one is Category and one is News. And we also have one relationship on it (one category has many news).

    Before implementing that 2 classes, I must build the base class for them, I called it is IEntity

        public interface IEntity
        {
            /// <summary>
            /// Gets or sets the id.
            /// </summary>
            /// <value>The id.</value>
            int Id { getset; }
        }

    Next I created the based class that implement the IEntity, purpose of this base class is store something that you think it common and share for derive-classes.

        public abstract class EntityBase : IEntity
        {
            /// <summary>
            /// Gets or sets the id.
            /// </summary>
            /// <value>The id.</value>
            public virtual int Id { getset; }

            /// <summary>
            /// Gets or sets a value indicating whether this instance is delete.
            /// </summary>
            /// <value><c>true</c> if this instance is delete; otherwise, <c>false</c>.</value>
            public virtual bool IsDelete { getset; }

            /// <summary>
            /// Gets or sets the created date.
            /// </summary>
            /// <value>The created date.</value>
            public virtual DateTime CreatedDate { getset; }

            /// <summary>
            /// Gets or sets the description.
            /// </summary>
            /// <value>The description.</value>
            public virtual string Description { getset; }
        }

    Read the code convention carefully before you start to code the entity class http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx. Next I implement 2 classes (called it is entity) as below:

        public class Category : EntityBase
        {
            /// <summary>
            /// Gets or sets the name.
            /// </summary>
            /// <value>The name.</value>
            public virtual string Name { getset; }

            private readonly ICollection<News> _news;

            /// <summary>
            /// Initializes a new instance of the <see cref="Category"/> class.
            /// </summary>
            public Category()
            {
                _news = new List<News>();
            }

            /// <summary>
            /// Gets the news.
            /// </summary>
            /// <value>The news.</value>
            public virtual ICollection<News> News
            {
                [DebuggerStepThrough]
                get { return _news; }
            }
        }

    And,

        public class News : EntityBase
        {
            /// <summary>
            /// Gets or sets the title.
            /// </summary>
            /// <value>The title.</value>
            public virtual string Title { getset; }

            /// <summary>
            /// Gets or sets the content.
            /// </summary>
            /// <value>The content.</value>
            public virtual string Content { getset; }

            /// <summary>
            /// Gets or sets the category.
            /// </summary>
            /// <value>The category.</value>
            public virtual Category Category { getset; }

            /// <summary>
            /// Initializes a new instance of the <see cref="News"/> class.
            /// </summary>
            public News()
            {
            }
        }

    • Mapping entity with database table

    One feature that I like the EF4 CTP4 is we can create the mapping class for entity with the database schema. I used to coding on Fluent NHibernate for short time, when EF still supported the mapping class yet, and now it is the time I try to use the EF4 with mapping classes. Everyone also knew the hell when you used mapping file on XML in old days. That problem happened when you type wrong something in XML file. The errors happen consequence, I called it is chain of errors. Luckily, the community published the Fluent NHibernate, which is a good ORM mapping I have ever used. It is integrated with strong type for typing mapping configuration. And now the EF4 CTP4 also supports the same. And even it is easily understanding than Fluent NHibernate. Try to understanding the relationship in EF4 before you implement mapping class.

    Mapping for Category:

        public class CategoryMapping : EntityConfiguration<Category>
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CategoryMapping"/> class.
            /// </summary>
            public CategoryMapping()
            {
                HasKey(a => a.Id);

                Property(a => a.Id).IsIdentity();
                Property(a => a.Name).IsRequired().HasMaxLength(50);
                Property(a => a.IsDelete);
                Property(a => a.CreatedDate);
                Property(a => a.Description).HasMaxLength(500);

                MapSingleType(a => new
                {
                    ID = a.Id,
                    a.Name,
                    a.IsDelete,
                    a.CreatedDate,
                    a.Description
                })
                .ToTable("Categories");
            }
        }

    And News,

        public class NewsMapping : EntityConfiguration<News>
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="NewsMapping"/> class.
            /// </summary>
            public NewsMapping()
            {
                HasKey(a => a.Id);

                Property(a => a.Id).IsIdentity();
                Property(a => a.Title).IsRequired().HasMaxLength(500);
                Property(a => a.Content).IsRequired().HasMaxLength(1000);
                Property(a => a.IsDelete);
                Property(a => a.CreatedDate);
                Property(a => a.Description).HasMaxLength(500);

                MapSingleType(a => new
                {
                    ID = a.Id,
                    CategoryId = a.Category.Id,
                    a.Title,
                    a.Content,
                    a.IsDelete,
                    a.CreatedDate,
                    a.Description
                })
                .ToTable("News");
            }
        }

    If you are familiar with Fluent NHibernate mapping, it is enough simple for you to understanding, isn’t it? If you are new person, it is not problems. Go to http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx, read it, and you shall clear.

    • Build your DbContext, DbContext factory

    Now, we shall start to investigate the DbContext, new features in CTP4, and next step we shall implementation the DbContext Factory for getting new DbContext’s instance. Because the DbContext is very complex and long code if your application become larger in the future, so I build it is a partial class and separated it to small classes.

        public partial class CSPDbContext : DbContext
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="CSPDbContext"/> class.
            /// </summary>
            /// <param name="model">The model.</param>
            public CSPDbContext(DbModel model)
                : base("CallStoreProc", model)
            {
            }
         }
        public partial class CSPDbContext
        {
            /// <summary>
            /// Called when [model creating].
            /// </summary>
            /// <param name="modelBuilder">The model builder.</param>
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Configurations.Add(new CategoryMapping());
                modelBuilder.Configurations.Add(new NewsMapping());
            }

            /// <summary>
            /// Gets or sets the categories.
            /// </summary>
            /// <value>The categories.</value>
            public DbSet<Category> Categories { getset; }

            /// <summary>
            /// Gets or sets the news.
            /// </summary>
            /// <value>The news.</value>
            public DbSet<News> News { getset; }
        }

    As you see on the OnModelCreating method, I overridden it and added 2 mapping files into ModelBuilder. And I also exported 2 DbSets for outside could access and used it.

    Next, I must build the DbContext Factory, and first thing is a contract for it

    And detail's implementation is

        public interface IDatabaseFactory : IDisposable
        {
            /// <summary>
            /// Gets this instance.
            /// </summary>
            /// <returns></returns>
            DbContext Get();
        }
        public class DatabaseFactory : IDatabaseFactory
        {
            private static readonly ModelBuilder builder = CreateModelBuilder();
            private readonly DbProviderFactory _providerFactory;
            private readonly string _connectionString;

            //private ObjectContext _objectContext;
            private DbContext _dbContext;

            /// <summary>
            /// Initializes a new instance of the <see cref="DatabaseFactory"/> class.
            /// </summary>
            /// <param name="providerFactory">The provider factory.</param>
            /// <param name="connectionString">The connection string.</param>
            public DatabaseFactory(DbProviderFactory providerFactory, string connectionString)
            {
                this._providerFactory = providerFactory;
                this._connectionString = connectionString;
            }

            /// <summary>
            /// Gets this instance.
            /// </summary>
            /// <returns></returns>
            public DbContext Get()
            {
                if (_dbContext == null)
                {
                    var model = builder.CreateModel();

                    _dbContext = new CSPDbContext(model);

                    return _dbContext;
                }

                return _dbContext;
            }

            /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            [DebuggerStepThrough]
            public void Dispose()
            {
                if (_dbContext != null)
                {
                    _dbContext.Dispose();
                }
            }

            /// <summary>
            /// Creates the model builder.
            /// </summary>
            /// <returns></returns>
            private static ModelBuilder CreateModelBuilder()
            {
                ModelBuilder modelBuilder = new ModelBuilder();

                IEnumerable<Type> configurationTypes = typeof(DatabaseFactory).Assembly
                                                                              .GetTypes()
                                                                              .Where(type => type.IsPublic && type.IsClass && !type.IsAbstract && !type.IsGenericType && typeof(StructuralTypeConfiguration).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null));

                foreach (StructuralTypeConfiguration configuration in configurationTypes.Select(type => (StructuralTypeConfiguration)Activator.CreateInstance(type)))
                {
                    modelBuilder.Configurations.Add(configuration);
                }

                return modelBuilder;
            }
        }

    This is a factory that I learnt from Shrinkr project on Codeplex http://shrinkr.codeplex.com/

    Part 2: Repository and Unit of Work on Entity Framework 4

    Part 3: Invoke store procedure in ADO.NET Entity Framework 4