【问题标题】:Modifying ProfileBase ConnectionString dynamically动态修改 ProfileBase ConnectionString
【发布时间】:2025-12-22 09:50:12
【问题描述】:

我有以下代码,我想用它来修改ProfileBase connectionString:

ProfileBase profile = ProfileBase.Create(username);

string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;

FieldInfo connectionStringField = profile.Providers["MySqlProfileProvider"].GetType().BaseType.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);

profile["FirstName"] = firstName;
profile["Surname"] = surname;

profile.Save();

首先connectionStringField 总是返回为空,但是我可以看到profile.Providers 确实包含MySqlProfileProvider。这是在我的Web.Config 中指定的:

<profile defaultProvider="MySqlProfileProvider">
  <providers>
    <clear/>
    <add name="MySqlProfileProvider" connectionStringName="MyApp" applicationName="MyApp" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
  <properties>
    <add allowAnonymous="false" defaultValue="" name="FirstName" readOnly="false" serializeAs="String" type="System.String"/>
    <add allowAnonymous="false" defaultValue="" name="Surname" readOnly="false" serializeAs="String" type="System.String"/>
  </properties>
</profile>

我的问题是connectionStringField 怎么会返回为空?这是否意味着我不能像通常使用自定义MembershipProvider 那样通过覆盖其Initialize 方法来修改连接字符串?

【问题讨论】:

  • ASP.NET 网站或项目模板?
  • @IrishChieftain ASP.NET 项目(MVC w/ WCF w/ EF)。
  • 您要取回 FirstName 和 Surname 属性吗?
  • @IrishChieftain 是的,他们都很好,而且一直都是。唯一的问题是我现在尝试在 profile.Save(); 方法之前更新连接字符串并且我的代码没有成功。
  • Fulvio,如果它与 EF 相关,我不知道。希望有更多知识的人能够回答它。调试的时候能看到'StoreConnection.ConnectionString'的值吗?

标签: c# asp.net membership-provider sqlprofileprovider


【解决方案1】:

你减少了一个太多的基本类型:

.Providers["MySqlProfileProvider"].GetType()**.BaseType**.GetField
.Providers["MySqlProfileProvider"].GetType().GetField

以下代码应该可以工作:

string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
Type type = profile.Providers["MySqlProfileProvider"].GetType();
FieldInfo connectionStringField = type.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);

【讨论】: