Click here to Skip to main content
15,881,882 members
Articles / Web Development / XHTML

ASP.NET Providers for the ADO.NET Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.90/5 (27 votes)
15 Nov 2014CPOL3 min read 210.9K   2.5K   94   58
The introduction of the ADO.NET Entity Framework implicitly created the need for ASP.NET providers such as membership, role and profile that leverage this new technology.

Introduction

One of the most powerful improvements of ASP.NET 2.0 was truly the introduction of the membership, role and profile providers. They allow to rapidly integrate user management, role based security as well as visitor based page customization into your ASP.NET application. The name already indicates that they all implement the provider model design pattern.

Unfortunately, Microsoft doesn't have these providers ready to download leveraging the ADO.NET Entity Framework.

The downloadable source from this article provides a ready-to-use implementation for the above mentioned providers. The following article gives a quick overview about providers and it describes what it takes to get the provided source up and running.

In order to understand the source, sound knowledge of LINQ is inevitable. Furthermore, it is important that readers understand the philosophy behind ASP.NET providers.The following link gives a good overview of the ASP.NET providers.

Background

Provider Model Design Pattern

AspNetEFProviders/provider_overview.JPG

The provider model pattern was designed to provide a configurable component for data access which is defined from the web.config. The Provider interfaces between the Business logic and Data Access. The actual concrete implementation of the provider is defined in the web.config. Custom providers can be built and configured in the web.config without changing the application design. Providers are a subclass of the ProviderBase class and typically instantiated using a factory method.

Various providers for the same purpose can co-exist and easily be configured in the web.config.

Database Schema

The database schema is closely related to the one that gets created by aspnet_regsql.exe:

AspNetEFProviders/provider_database_schema.JPG

The resulting Entity Model looks like the following:

AspNetEFProviders/provider_entity_model.JPG

Other than Microsoft's ASP.NET providers for SQL, the presented solution here does not use stored procedures. Instead, all the queries are implemented in the respective providers source using LINQ.

Exposed APIs

Membership Provider
C#
void Initialize(string name, NameValueCollection config)

MembershipUser CreateUser(string username, string password, string email,
            string passwordQuestion, string passwordAnswer,
            bool isApproved,object providerUserKey, 
            out MembershipCreateStatus status)

bool ChangePasswordQuestionAndAnswer(string username, string password,
                string newPasswordQuestion, string newPasswordAnswer)

string GetPassword(string username, string answer)

bool ChangePassword(string username, string oldPassword, string newPassword)

string ResetPassword(string username, string answer)

void UpdateUser(MembershipUser membershipUser)

bool ValidateUser(string username, string password)

bool UnlockUser(string username)

MembershipUser GetUser(object providerUserKey, bool userIsOnline)

string GetUserNameByEmail(string email)

bool DeleteUser(string username, bool deleteAllRelatedData)

MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)

int GetNumberOfUsersOnline()

MembershipUserCollection FindUsersByName
	(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)

MembershipUserCollection FindUsersByEmail
	(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
Role Provider
C#
void Initialize(string name, NameValueCollection config)

bool IsUserInRole(string username, string roleName)

string[] GetRolesForUser(string username)

void CreateRole(string roleName)

bool DeleteRole(string roleName, bool throwOnPopulatedRole)

bool RoleExists(string roleName)

void AddUsersToRoles(string[] userNames, string[] roleNames)

void RemoveUsersFromRoles(string[] userNames, string[] roleNames)

string[] GetUsersInRole(string roleName)

string[] GetAllRoles()

string[] FindUsersInRole(string roleName, string usernameToMatch)
Profile Provider
C#
void Initialize(string name, NameValueCollection config) 

SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, 
				SettingsPropertyCollection properties)

void SetPropertyValues(SettingsContext context, 
		SettingsPropertyValueCollection properties)

int DeleteProfiles(ProfileInfoCollection profiles)

int DeleteProfiles(string[] usernames)

int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, 
			DateTime userInactiveSinceDate)

int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, 
				DateTime userInactiveSinceDate)

ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, 
				int pageIndex, int pageSize, out int totalRecords)

ProfileInfoCollection GetAllInactiveProfiles
		(ProfileAuthenticationOption authenticationOption, 
		DateTime userInactiveSinceDate, int pageIndex, 
		int pageSize, out int totalRecords)

ProfileInfoCollection FindProfilesByUserName
		(ProfileAuthenticationOption authenticationOption, 
		string usernameToMatch, int pageIndex, 
		int pageSize, out int totalRecords)

ProfileInfoCollection FindInactiveProfilesByUserName
		(ProfileAuthenticationOption authenticationOption, 
		string usernameToMatch, 
		DateTime userInactiveSinceDate, int pageIndex, 
		int pageSize, out int totalRecords)

How To Use the Provided Solution?

The three in this solution contained providers are connected but it shouldn't be too much work to pull them apart if not all of them are required. There are two ways to use the source:

  1. Use the provided Entity Model to connect to an existing or new database.
  2. Extend an existing database and hence the existing Entity Model and replace the data context used by the providers with the existing data context.

In general, the following steps have to be applied to get the first approach up and running:

  1. Create a new database (e.g., EFDataModel).
  2. Run the CreateTables.sql script located in the DatabaseScripts solution folder on the new database.
  3. Modify the connection string for the Entity Framework in the App.config file of the SmartSoft.EFProviders.DataLayer project.
  4. Modify connection string for the Entity Framework in the Web.config file of the Web application.
  5. Configure the providers in the Web.config as follows:
XML
<!-- Membership configuration -->
<membership defaultProvider="EFMembershipProvider" userIsOnlineTimeWindow="15">
    <providers>
        <add name="EFMembershipProvider" 
             type="HelveticSolutions.EFProviders.Web.Security.EFMembershipProvider, 
              HelveticSolutions.EFProviders.Web, Version=1.0.0.0, Culture=neutral,
              PublicKeyToken=53fb08796b3f3bb2" 
             connectionStringName="EFProviderConnection" 
             enablePasswordRetrieval="true" 
             enablePasswordReset="true" 
             requiresQuestionAndAnswer="true"
             writeExceptionsToEventLog="true" />
    </providers>
</membership>
<machineKey validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA174257
    2A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
       decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F" 
       validation="SHA1"/>
<!-- Role configuration -->
<roleManager enabled="true" defaultProvider="EFRoleProvider">
    <providers>
        <add name="EFRoleProvider" 
             type="HelveticSolutions.EFProviders.Web.Security.EFRoleProvider, 
              HelveticSolutions.EFProviders.Web, Version=1.0.0.0, Culture=neutral, 
              PublicKeyToken=53fb08796b3f3bb2" 
             connectionStringName="EFProviderConnection" />
    </providers>
</roleManager>
<!-- Profile configuration -->
<profile enabled="true" 
    defaultProvider="EFProfileProvider" 
    inherits="EFProvidersWebApplication.MyProfile" 
    automaticSaveEnabled="true">
    <providers>
        <add name="EFProfileProvider" 
             type="HelveticSolutions.EFProviders.Web.Profile.EFProfileProvider, 
              HelveticSolutions.EFProviders.Web, Version=1.0.0.0, Culture=neutral, 
              PublicKeyToken=53fb08796b3f3bb2" 
             connectionStringName="EFProviderConnection"/>
    </providers>
</profile>

Background

Wherever possible, LINQ queries were written to use expression trees rather than delegates. This article greatly describes the difference.

History

  • 29/10/2008 - Initial article posted
  • 01/08/2009 - New EFRoleProvider and EFProfileProvider, improved EFMembershipProvider
  • 14th November 2014 - Namespace corrected

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Swissworx
Australia Australia
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5

My company: Swissworx
My blog: Sitecore Experts

Hopp Schwiiz Smile | :)

Comments and Discussions

 
GeneralUnlockUser Pin
Kevin Slesinsky20-Aug-09 10:32
Kevin Slesinsky20-Aug-09 10:32 
GeneralGreat stuff! Pin
celtonthenet11-Aug-09 1:29
celtonthenet11-Aug-09 1:29 
GeneralRe: Great stuff! Pin
Michael Ulmann15-Nov-14 9:47
Michael Ulmann15-Nov-14 9:47 
GeneralProfile Provider with EF "normal" SQL Profile table Pin
shapper5-Aug-09 16:09
shapper5-Aug-09 16:09 
GeneralSQL Script Pin
shapper5-Aug-09 3:12
shapper5-Aug-09 3:12 
GeneralThanks. One suggestion and one question Pin
shapper3-Aug-09 14:54
shapper3-Aug-09 14:54 
GeneralRe: Thanks. One suggestion and one question Pin
Michael Ulmann3-Aug-09 16:02
Michael Ulmann3-Aug-09 16:02 
GeneralRe: Thanks. One suggestion and one question Pin
shapper4-Aug-09 6:34
shapper4-Aug-09 6:34 
Hi Michael,

I have been going around your SQL code. I made a few changes (I didn't test it yet).

What is strange is that you don't have delete cascade on Users/Profiles and on Applications/Users.

If a User is deleted shouldn't its Profiles being deleted.

I am posting my SQL (It is cleaner. I recoded not using SQL Man. Studio)

Note that I didn't test it yet. I wanted to know your opinion about the cascade delete before.

create table dbo.Applications
(
	Id uniqueidentifier rowguidcol not null constraint DF_Applications_Id default (newid()),	  
	Description nvarchar(200) null,    
	[Name] nvarchar(100) not null,	
	  constraint PK_Applications primary key clustered (id)
)
create table dbo.Profiles
(
	UserId uniqueidentifier rowguidcol not null constraint DF_Profiles_UserId default (newid()),
	LastUpdatedDate datetime not null,
	PropertyNames ntext null,
	PropertyValuesBinary image null,
	PropertyValuesString ntext null,		
    constraint PK_Profiles primary key clustered (id)
)
create table dbo.Roles
(
	Id uniqueidentifier rowguidcol not null constraint DF_Roles_Id default (newid()),
	ApplicationId uniqueidentifier not null,
	Description nvarchar(200) not null,		
	[Name] nvarchar(100) not null,	
    constraint PK_Roles primary key clustered (id)
)
create table dbo.Users
(
	Id uniqueidentifier rowguidcol not null constraint DF_Users_Id default (newid()),
	ApplicationId uniqueidentifier not null,
	Comment nvarchar(200) null,
	CreationDate datetime null,
	Email nvarchar(100) not null,	
	FailedPasswordAnswerAttemptCount int null,
	FailedPasswordAnswerAttemptWindowStart datetime null,	
	FailedPasswordAttemptCount int null,
	FailedPasswordAttemptWindowStart datetime null,	
	IsAnonymous bit not null constraint DF_Users_IsAnonymous default (0),
	IsApproved bit not null constraint DF_Users_IsApproved default (1),
	IsLockedOut bit not null,
	IsOnline bit null,
	LastActivityDate datetime not null,
	LastLockedOutDate datetime null,
	LastLoginDate datetime null,	
	LastModified datetime null,
	LastPasswordChangedDate datetime null,	
	[Name] nvarchar(100) null,
	Password nvarchar(100) null,
	PasswordAnswer nvarchar(200) null,
	PasswordQuestion nvarchar(200) null,		
	Username nvarchar(50) not null,
    constraint PK_Users primary key clustered (id)
)
create table dbo.UsersRoles
(
	UserId uniqueidentifier not null,
	RoleId uniqueidentifier not null,
    constraint PK_UsersRoles primary key clustered (id)
)


And the restrictions:

alter table dbo.Roles 
add constraint FK_Roles_Applications foreign key (ApplicationId) references dbo.Applications(Id) on delete cascade on update cascade;

alter table dbo.Users
add constraint FK_Users_Applications foreign key (ApplicationId) references dbo.Applications(Id) on delete no action on update no action;

alter table dbo.UsersRoles
add constraint FK_UsersRoles_Roles foreign key(RoleId) references dbo.Roles(Id) on update cascade on delete cascade;
    constraint FK_UsersRoles_Users foreign key(UserId) references dbo.Users(Id) on update cascade on delete cascade;

alter table dbo.Profiles 
add constraint FK_Profiles_Users foreign key(UserId) references dbo.Users(Id) on delete no action on update no action;


Thanks,
Miguel
GeneralRe: Thanks. One suggestion and one question Pin
shapper4-Aug-09 6:36
shapper4-Aug-09 6:36 
GeneralRe: Thanks. One suggestion and one question Pin
Michael Ulmann4-Aug-09 20:46
Michael Ulmann4-Aug-09 20:46 
GeneralRe: Thanks. One suggestion and one question Pin
shapper5-Aug-09 1:35
shapper5-Aug-09 1:35 
GeneralRe: Thanks. One suggestion and one question Pin
shapper5-Aug-09 3:11
shapper5-Aug-09 3:11 
GeneralCool, thanks Pin
Thewak1-Aug-09 21:37
Thewak1-Aug-09 21:37 
GeneralRe: Cool, thanks Pin
Michael Ulmann15-Nov-14 9:47
Michael Ulmann15-Nov-14 9:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.