Customizing the EF Entity Templates

The nice thing about Entity Framework is that anytime you are using one of the entity template generation capabilities, they are pretty easily customizable. This, of course, means that you are NOT using the pure code-first API most likely (however, to an existing database defines a T4 template). In this blog post, we’re going to quickly update the T4 template to change the default rendering:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public int StateID { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
}

To add additional information that the application can later use for metadata purposes, such as the following:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public const string StateID_Name = "StateID";
    public int StateID { get; set; }
    
    public const int StateCode_MAX_LENGTH = 10;		
    public const string StateCode_Name = "StateCode";
    public string StateCode { get; set; }
    
    public const int StateName_MAX_LENGTH = 50;
    public const string StateName_Name = "StateName";
    public string StateName { get; set; }
}

Notice that each column has a constant defining the name, as well as a constant defining it’s max length defined in the database (if a string).

To do this, we need to open up the .tt file that generates each of the entities. In my version, around line 66, we have the following snippet.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {
#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#
    }
}

Notice that this snippet loops through each of the simple properties (the properties defined one for each column) and renders out a definition (note codeStringGenerator is a class defined in the T4 template that defines all of the markup. I didn’t choose to modify that here). To add the name constants and the max length constants, the updated samples were changed to the following code sample. Comments below indicate the changes made.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    //edmProperty of type EdmProperty
    foreach (var edmProperty in simpleProperties)
    {
        //Check max length - if any max length, then write out a constant
	 if(edmProperty.MaxLength.HasValue)
                {
                        #>
 
                        public const int <#= edmProperty.Name #>_MAX_LENGTH = 
                            <#= edmProperty.MaxLength.Value #>;
 
                        <#
                }	


         public const string <#= edmProperty.Name #>_Name = 
               "<#= edmProperty.Name #>";

    <#=codeStringGenerator.Property(edmProperty)#>
    <#
    }
}

Here we add constants to the output of the properties and everything generates great. You may say it would be better to use attributes; that is possible as well, but for that I’d recommend editing the CodeStringGenerator class (in the T4 template) and update the Property method directly instead.

The T4 template is available here: http://pastebin.com/42NiuwDE

Discussing ASP.NET MVC Model Binding With Hidden Data

If you have taken over an MVC application, you may have come across a dilemma like the following. Notice that in a view, within a form, you’ll see a group of hidden fields mixed in with a form like the following.

Html.HiddenFor(i => i.ContactID)
Html.HiddenFor(i => i.ContactTypeID)
Html.HiddenFor(i => i.ContactDescription)
Html.HiddenFor(i => i.ContactTypeDescription)
Html.HiddenFor(i => i.OrganizationID)

Html.LabelFor(i => i.OrganizationName, new { @class = "control-label" }) Html.TextBoxFor(i => i.OrganizationName, new { @class = "form-control" })
@* and so on *@

My example had five hidden fields, but I’ve seen a lot more. These fields are not useful to the form per se; the user doesn’t enter them. However, the information is important to the records about to be updated in the database, and thus are included in the form as hidden fields for that reason. However, another reason is it acts as a quasi-ViewState mechanism that makes it very easy to replenish the following model:

public class ContactInfoModel
{
    public int? ContactID { get; set; }

    public int? ContactTypeID { get; set; }

    public string ContactDescription { get; set; }

    public string ContactTypeDescription { get; set; }

    public int? OrganizationID { get; set; }

    public string OrganizationName { get; set; }

    /* and so on */
}

[HttpPost]
public ActionResult Contact(ContactInfoModel model)
{
 ...
}

While OrganizationName and the other unlisted properties came from the form, the first five properties (and potentially more) are stored in the hidden field. The hidden field makes it nice and easy to replenish this model, and than allow the developer to use the parameters in the post action. MVC does a very nice job posting the values back to the server and populating these properties.

However, notice I said before, that this was a ViewState-like solution? It’s not quite within the model of ViewState because all of the parameters are embedded in the form in clear text. In most systems, the user is required to login before they can ever get to a page that contains this type of information. Either way, the users have the tools (IE developer tools, Firebug) to inspect and change the values in the hidden fields if they so desired. That is where the danger can lie.

Here’s the other side of the conundrum: if we don’t reload the parameters, what do we do? If we didn’t include the hidden fields, the first five parameters are not loaded from the client and thus the model is partially replenished. In most cases, these pieces of information might not be needed anyway (with the exception of OrganizationID in our scenario).

The application can certainly requery the information it needs, but then the information gets reloaded on every postback, which can get more expensive. The application could also use Session to store the information fields too.

I’m not saying “NEVER use hidden fields”, but I’m debating the value of a large number of hidden fields for replenishing the model. I probably fit within the category of storing any relative information in Session or requerying the information from the database, depending on how much information we are talking about. What is your thoughts or preference? Using hidden fields, session, database?

Using Interfaces for ASP.NET MVC Model Binding

Sometimes you may want to support view reuse, where a partial view displays a portion of the application in a reusable fashion. Suppose you had the following entity which has a bunch of properties.

public class Customer
{
   public int CustomerID { get; set; }

   public string FirstName { get; set; }

   public string LastName { get; set; }

   public string AccountNumber { get; set; }

   .
   .
}

Suppose you wanted to use a PartialView because it was an AJAX widget with a JavaScript initialization script, and defining a reusable control made it really easy to support this. MVC defines a strongly typed model reference, so does that mean we have to bind the model directly to Customer, or define a custom type for an editor template?

We actually can use interfaces by adding the following:

public interface IAccountEntity
{
   string AccountNumber { get; set; }
}

We can define this in a partial view:

@model IAccountEntity

@Html.TextBoxFor(i => i.AccountNumber)

   $(function() {
      /* Registration Script */
   });

And then use it in our EditCustomer view, as a partial with the existing model:

@Html.Partial("EditAccountNumber", Model)

Since Model (of type Customer) is also IAccountEntity, this translates just fine with MVC. It works just as well when you use hierarchies too. For instance, Customer implements IAccountEntity, but what if we had a CustomerModel class above Customer like:

CustomerModel
     Customer : IAccountEntity
        AccountNumber

If EditCustomer view looks like the following:

@model CustomerModel
.
.

<div class="form-group">
   <label class="col-md-2 control-label">First Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.FirstName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">Last Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.LastName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">AccountNumber</label>
   <div class="col-md-10">
       @Html.Partial("EditAccountNumber", Model)
   </div>
</div>

Notice how the model is passed in directly; this won’t work for our scenario, because the EditAccountNumber expects an IAccountEntity, and requires that the partial be passed in this way:

@Html.Partial("EditAccountNumber", Model.Customer)

However, that doesn’t work for our needs, if our controller has a post operation of the following:

[HttpPost]
ActionResult Edit(CustomerModel model)
{
    if (string.IsNullOrEmpty(model.AccountNumber))
    {
      //This will always be the case, why?  See below
    }
}

Welcome to one of the challenges of MVC model binding. In the previous form, the first/last name and account number would post back to the server something like:

Customer__FirstName: BOB
Customer__LastName: SMITH
AccountNumber: ABC123

What needs to happen is the “AccountNumber” key also needs to be Customer__AccountNumber for it to successfully bind back to the server. You can add AccountNumber as a parameter to the post method, or we can add another interface that supports our hierarchy, and add this interface to the CustomerModel:

//Interface definition
public interface IAccountNumberModel
{
    IAccountNumberEntity Customer { get; set; }
}

//Update to the model class
public class CustomerModel : IAccountNumberModel
{

   public Customer Customer { get; set; }

   IAccountNumberEntity IAccountNumberModel.Customer { get; set; }

}

Here IAccountNumberModel has the same property name as CustomerModel; that’s important to make sure the model binding name structure matches. Now we can pass in the CustomerModel to the EditAccountNumber view with these modifications:

//EditAccountNumber
@model IAccountNumberModel

@Html.TextBoxFor(i => i.Customer.AccountNumber)
.
.

//EditCustomer:
.
.
@Html.Partial("EditAccountNumber", Model)

Since CustomerModel implements IAccountNumberModel, and this matches the type of model on our partial view, everything binds correctly.

Authenticating over AD with the ADMembershipProvider

Want to authenticate against AD but don’t want to use LDAP directly? Would you like to use the AD membership provider, but don’t want tied into the membership API? No problem! That’s because you can programmably create the membership provider, provide some configuration options, and then made an API call to check the login status. The code is very simply the following:

var membershipProviderName = "Provider"; // Does not need to be in web.config
var connectionStringName = "SomeConnectionString";
var config = new NameValueCollection();

config.Add("connectionStringName", connectionStringName);

var provider = new ActiveDirectoryMembershipProvider();
provider.Initialize(providerName, config);

var isValidUser = provider.ValidateUser(user, password);

And that’s all it takes. The provider name is the name you would normally see in the configuration file; we’re defining it during initialization. Next, we need to create configuration options. Our implementation only supplies the connection string name defined in the connection strings setting. Define a connection string, with the name supplied above, that points to the LDAP store. Note that no membership API needs to exist in the

Next, we create and initialize the provider, and use the provider to validate the credentials. Is there an expense to building this up every time? I haven’t tested it out, but logically it seems that would be the case. Just plan it’s use accordingly.

Adding Testability Through Mocking Workarounds

Sometimes when you are developing code, you are bound to run into something that is a roadblock from unit testing. That is why frameworks like TypeMock are so great; TypeMock is a powerful mocking tool that can reflect and override any code you feel like mocking, even if that code is internal. If you are using an open source tool like Moq or RhinoMocks, you don’t have the ability to mock non-virtual (non-overridable for the VB crowd) or private methods. TypeMock allows you to do it all. As far as my open-source or free mocking tools go, I like Moq a lot. The interface is simple, straightforward, and is as functional as any of the other frameworks out there. (Note this post isn’t meant to be a selling point for Moq, but it’s useful to know as my examples will be using it.)

As an architect, your bound to run into segments of code that are like the following:

[ExportType(typeof(ICacheLoadingService))]
public class CacheLoadingService : ICacheLoadingService
{
    //A quick wrapper around ASP.NET cache
    private ICache _cache = null;

    //DI constructor injection of relationships
    public CacheLoadingService(ICache cache)
    {
        _cache = cache;
    }
   
    public void Init()
    {
        //instantiate database connector that has a customized constructor that can't be easily mocked
        IDbConnector ctx = new SQLServerDBConnector();
        //Write the commonly used reference data to cache
        _cache.Add(typeof(State), ctx.Get().ToList());
        .
        .
    }

}

Here we have a few things. ICache is a simple wrapper around ASP.NET cache, and is loaded in the constructor of the service (not relevant to this article; just note for reference). Later on, Init() opens up a database connection, which we have no control over creating, but does implement an interface. This is there the challenge for unit testing lies, and we’ll see a workaround very soon. Lastly, [ExportType] is from an open-source project I created to make registration of dependencies very simple.

Back to IDbConnector; with the current setup, using a framework like Moq makes testing this class hard without a live actual database connection. But with a little help, we can add a wrapper around the creation process easier. In walks our little helper:

public interface ICreator
{
   T Create(Func fn);
}

[ExportType(typeof(ICreator))]
public class ObjectCreator : ICreator
{
   public T Create(Func fn)
   {
      return fn();
   }
}

While this solution seems redundant and pointless, this actually solves the problem above. Because we use an object, defining an interface, to create the object, it makes mocking the object that much easier. Changing our init method from above, we add the following to CacheLoadingService:

[ExportType(typeof(ICacheLoadingService))]
public class CacheLoadingService : ICacheLoadingService
{
    private ICache _cache = null;
    private ICreator _creator = null;

    public CacheLoadingService(ICache cache, ICreator creator)
    {
        _cache = cache;
        //passed in through dependency injection
        _creator = creator;
    }
   
    public void Init()
    {
        //ICreator takes the pain out of testing, which you will see next
        IDbConnector ctx = _creator.Create(() => new SQLServerDBConnector());
        _cache.Add(typeof(State), ctx.Get().ToList());
        .
        .
    }

}

Our change is subtle, and it required more code (to create the new class), and a little overhead, sure. But now let’s look at how we can test the DB connection, which wasn’t possible to do earlier. The following is the test logic using Moq:

var creator = new Mock();
creator.Setup(i => i.Get()).Returns(stateTestData);
.
.

var cache = new Mock();
cache.Setup(i => i.Add(typeof(State), It.IsAny<List>()).Verify();

var service = new CacheLoadingService(cache.Object, creator.Object);
service.Init(); //now our DB connection is mocked

cache.Verify();

Now in this test, we verify the DB connection returns the test data and actually gets passed to the cache. This is a very simple way to test objects with external dependencies, like databases, files, etc. Databases hinder unit testing because it breaks the isolation aspect (but is fine for integration tests). And our cache.Verify() statement verifies that everything gets added to the cache as expected.

We managed to take code that was hard to test and provide a simple way of testing it in this article. This is not a one-size-fits-all solution, but it does add testability to a lot of bases you never previously expected, and only adds a small overhead to the application.