2012-04-12 40 views
1

我有下面的代码,我想用它来修改ProfileBase的connectionString:修改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方法修改连接字符串?

+0

ASP.NET网站或者项目模板? – IrishChieftain 2012-04-12 02:36:22

+0

@IrishChieftain ASP.NET项目(MVC w/WCF w/EF)。 – fuzz 2012-04-12 04:00:27

+0

你是否获得名字和姓氏属性? – IrishChieftain 2012-04-12 04:08:14

回答

2

你去太多了基本类型下来:

.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); 
+0

这似乎很好地工作,谢谢队友。 – fuzz 2012-04-13 01:08:47