Profile Addendum

Thursday, December 29, 2005

There are a couple articles on the web saying you can use a base Profile class like so:

using System;
using System.Web.Profile;

public class CustomProfile : ProfileBase
{    
    
public string PetName
    {
        
get { return _petName; }
        
set { _petName = value; }
    }
    
private string _petName;      
}

Then use the inherits attribute in web.config like so:

<profile inherits="CustomProfile"/>

I hope I can save you some time by pointing out the above setup doesn’t work.

You’ll find the HttpContext contains a non-null Profile object, but SQL Profiler will confirm that ASP.NET never populates the object with data from the database. Perhaps the above approached worked in pre-RTM bits, I’m not sure.

Here is a CustomProfile that will fetch and save data properly:

using System;
using System.Web.Profile;

public class CustomProfile : ProfileBase
{    
    
public string PetName
    {
        
get { return (string)base["PetName"]; }
        
set { base["PetName"] = value; }
    }   
}

With the above class, Profiler shows the expected “exec dbo.aspnet_Profile_GetProperties” and “exec dbo.aspnet_Profile_SetProperties” commands and it all works as expected.

ASP.NET uses a lazy-load pattern for the Profile object. The runtime doesn’t touch the database until execution first reaches SettingsBase.GetPropertyValueByName (SettingsBase is the parent class of ProfileBase). GetPropertyValueByName will ask the Profile provider to fetch all properties from the database.

The good news is, if a web form doesn’t use any Profile properties, you don’t pay the overhead of a database hit.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!