2013-05-15 48 views
3

我使用ASP.NET MVC4,我設置的自定義配置文件類在本article about universal membership providersASP.NET成員:自定義配置文件繼承

public class CustomProfile : ProfileBase 
{ 
    public DateTime? Birthdate 
    { 
     get { return this["Birthdate"] as DateTime?; } 
     set { this["Birthdate"] = value; } 
    } 

    public static CustomProfile GetUserProfile(string username) 
    { 
     return Create(username) as CustomProfile; 
    } 

    public static CustomProfile GetUserProfile() 
    { 
     var user = Membership.GetUser(); 
     if (user == null) 
      return null; 

     return Create(user.UserName) as CustomProfile; 
    } 
} 

說明我還更新了配置文件中的條目在web.config中定義:

<profile defaultProvider="DefaultProfileProvider" inherits="MembershipTestsV3.Models.CustomProfile"> 
    <providers> 
    <add name="DefaultProfileProvider" 
     type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
     connectionStringName="DefaultConnection" 
     applicationName="MyAppName" /> 
    </providers> 
</profile> 

這意味着我可以實例像這樣我的自定義配置文件對象時,我想:

var customProfile = HttpContext.Profile as CustomProfile; 

現在,我希望有許多類型的配置文件繼承此基地;如AdminUserProfile,或SupervisorProfile:

public class SupervisorProfile : CustomProfile 
{ 
    public string Department 
    { 
     get { return this["Department"] as string; } 
     set { this["Department"] = value; } 
    } 
} 

但是,每次我試着投我得到一個空引用異常對象:

var customProfile = HttpContext.Profile as SupervisorProfile; 

我知道,在數據庫級別的配置文件將只保存同一張表上的所有相關列,我只想在服務層上組織屬性。有沒有辦法做到這一點?

回答

3

這是不可能的ProviderModel內,但如果你圍繞它建立一個層就可以實現它。您可以採取以下幾種方式:

  • 將相關信息保存在另一個表中,並在該配置文件中保存對該信息的引用。然後,您可以只保留一個簡單的配置文件類,並使用存儲庫或其他相關類來獲取額外信息(可能是具有子類型的基本類型)。這將有利於對象組合而不是繼承。
  • 保留一個簡單的具有所有屬性的配置文件類。而不是直接從HttpContext的獲取配置文件,你可以圍繞它建立一個層(工廠如果你願意),該檢查的實例,並返回一個不同的類型,根據不同的價值觀輪廓
+0

全體成員計劃內似乎「關閉」。一方面是通用提供者(Universal Providers)得到了很好的實現,但是屬性是一個擴展的麻煩(因爲它們被存儲爲具有通用結構的單個表上的blob),另一方面是SimpleMembership,它允許CodeFirst用於配置文件表,但與許多預先製作的管理工具(如SecurityGuard)不兼容。 – amhed