2

我正在使用 ASP.NET MVC4,我已经设置了一个自定义配置文件类,如这篇关于通用会员提供程序的文章中所述

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;

我知道在数据库级别,配置文件只会将所有相关列保存在同一个表中,我只想在服务层上组织属性。有没有办法做到这一点?

4

1 回答 1

3

这在 ProviderModel 内部是不可能的,但是如果你围绕它构建一个层,你就可以实现它。您可以采取多种方式:

  • 将相关信息保存在另一个表中,并将对该信息的引用保存在配置文件中。然后,您可以只保留一个简单的配置文件类并使用存储库或其他相关类来获取额外信息(可能是具有子类型的基本类型)。这将有利于对象组合而不是继承。
  • 保留一个具有所有属性的简单配置文件类。除了直接从 HttpContext 获取配置文件之外,您还可以围绕它构建一个层(如果您愿意的话,工厂),它检查实例并返回不同的类型,具体取决于配置文件中的值
于 2013-05-15T21:42:01.367 回答