TOP

Doing Web Development Better Part 2

Since last time, I have come further in the research on how to have more dynamic loading of entities using reflection and I’m displaying the different actions using partial views from my themes folder. That makes it possible for individual themes to override the layout of the generated pages.

Current Status

So the current status is that I have fully dynamic rendering for list of items and details on individual items. I have not yet added support for editing. The end results of what I’m working on, might be somewhat similar to the ASP.NET Dynamic Data technology from Microsoft. It does scaffolding of your data automatically. The difference obviously will be that mine are built on ASP.NET Web Pages and next version of Entity Framework. Other than sharing some general concepts, there are no similarities between my code and ASP.NET Dynamic Data.

Status Quo

Mikael Söderström made a good example on how you can combine Entity Framework and ASP.NET Web Pages, so I won’t bother doing the same. Check a bit down on this thread: http://forums.asp.net/t/1580303.aspx

What I want to avoid is the specific repositories, I want a single repository that is dynamic and can handle any entity type. I also want to avoid any logic inside the .cshtml that relates to the creation/reading of the entities. His example is still decent for those who want to go the “new, old route” of doing web development with Web Matrix. I’m on a mission to simplify this pattern.

Get Started

What I want to show today is how to dynamically create an instance of your entity and return that from your database. Create a new empty WebMatrix website and start writing some code.

Before we begin, make sure you have the latest version of Microsoft WebMatrix, SQL Server Compact Edition and Entity Framework CTP.

First you need to go through the example by Mikael that I linked too earlier, but you can replace the GuestbookRepository.cs with the code below and the default.cshtml will be different as well.

1. Create a new interface and call it IEntity. Just keep this empty for now.

2. Create a new class and call it Repository. Copy the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Helpers;

/// <summary>
/// Generic repository for all of your entity types.
/// </summary>
public class Repository<TContext> where TContext : DbContext
{
    private TContext _context;
    private string _entityTypeName;
    private Type _entityType;

    public Repository(string entityTypeName)
    {
        _entityTypeName = entityTypeName;
    }

    public TContext Context
    {
        get
        {
            if (_context == null)
            {
                _context = CreateContext();
            }

            return _context;
        }
    }

    private TContext CreateContext()
    {
        _entityType = Type.GetType(_entityTypeName);

        // Make sure that only IEntity objects are returned for security reasons. You don't want
        // code that allows users to initiate any objects on the server.
        if (!_entityType.Implements(typeof(IEntity)))
        {
            throw new ApplicationException("The specified entity does not implement the required IEntity interface.");
        }

        // Create an instance of the DbContext.
        var context = Activator.CreateInstance<TContext>();

        return context;
    }

    private dynamic GetSet()
    {
        // Get an instance of the DbSet.
        var set = Context.Set(_entityType);

        // Load all the values.
        set.Load();

        // Get the query values.
        return set.Local;
    }

    public void Load(IEntity entity)
    {
        
    }

    public void Add(IEntity entity)
    {
        
    }

    public dynamic LoadAll()
    {
        return GetSet();
    }

    public void Delete(IEntity entity)
    {
        
    }
}

Unfortunately this code only does listing of all the entities, through the LoadAll method. In one of my later blog posts, I will provide example that does all the normal CRUD operations for your entities.

3. Create a new .cshtml file and call it what you want. Paste the following code into the new file:

@{
    var entityType = UrlData[0];
    var action = UrlData[1];
    var id = UrlData[2];
    
    if (string.IsNullOrEmpty(entityType))
    {
        Response.Write("There is nothing to see here... - Jim Carrey, \"Lifeguard on Duty\"");
        Response.End();
    }
    
    var repository = new Repository<BlogCatalog>(entityType);
    var result = repository.LoadAll();
    Page.Model = result;
    
    var grid = new WebGrid(Page.Model);    
}

@grid.GetHtml()

The code has been simplified a bit, it doesn’t handle multiple types of listing. The “BlogCatalog” is the DbContext you created in the example by Mikael. Change that to whatever your own context is named.

Screenshot of the end result, this is the listing of my Author table.

Result

The Beginning of By Convention

That’s the early beginning of the framework that will make it even easier and better to develop web apps using Microsoft WebMatrix and ASP.NET Web Pages. The combination of ASP.NET Web Pages with Entity Framework and doing the code by convention, gives us a powerful tool where we avoid duplicate code and we don’t have to repeat yourselves too often.

Leave a Reply

Your email is never published nor shared.

You may use these HTML tags and attributes:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>