Month: June 2011

Somebody who followed an ASP.NET course with me couldn’t find the necessary plugs to add your own providers to the .NET infrastructure. Since more will probably benefit I’m sharing with you all the necessary steps.

So you have your users stored somewhere in a database and can’t use the out of the box implementations that ship with the .NET framework. What are the steps that you need to do?

First, create a class that inherits from the abstract MembershipProvider and implement all the functionality you want to support. The more you add the better all the components that rely on it will be able to function. To just get beyond an MVC3 login page or a login with an ASP.NET webcontrol you just need to implement the validate user method.

For this demonstration I’m just checking if I have a user with the same username in my database.

With our class in place we now need to plug it into the provider model, open your web.config navigate to the system.web node and configure your provider. If you added any additional configuration properties in your custom provider you can configure them there as well.

I’ve added a navigation property from Address to Customer and marked the Customer property as required. This basically is telling EF that there is a one to one mapping between the two and the primary key of the customer should be used in the relationship. The primary key of the customer will also become the primary key of the address. If you did not add the required attribute you’ll get an invalidoperationexception saying that it’s unable to determine the principal end of an association.

You saw that the WithRequiredPrincipal and Depedant actually have one taking a lambda and one with no arguments. This allows you to exclude a navigation property and still get a proper one to one mapping. Which brings me back to my starting point.

By default if you add ‘simple’ property types to your class (strings, ints,…), they are all translated into columns in the database. What if you had a group of properties that actually can have some functionality together. You also have this group of properties coming back at several places in your code base. You could introduce a base class in order to improve duplication but if the two entities are not really related you should stay away from overusing the inheritance approach. What you need here is a complextype. It was present in previous releases of the Entity Framework and can be used in 4.1.

Customer could also have a bunch of methods that acted upon the address fields, Employee could have the same properties, the same logic and an invoice probably also has an address. So let’s move the properties, and logic, into a new class called Address. I don’t want a separate table that contains all the addresses though, I want all of the address fields to be present in the customer, employee and invoice table.