Modifying ProfileBase ConnectionString dynamically

孤者浪人 提交于 2019-12-13 18:07:37

问题


I have the following code, which I want to use to modify the 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();

First of all the connectionStringField always comes back as null, however I can see that profile.Providers does contain MySqlProfileProvider. This is specified within my 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>

My question is how come connectionStringField is coming back as null? Does this mean I cannot modify the connection string like I normally would with a custom MembershipProvider by overriding its Initialize method?


回答1:


You went one too many basetypes down:

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

The following code should work:

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);


来源:https://stackoverflow.com/questions/10116626/modifying-profilebase-connectionstring-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!