实体框架DBContext,运行时的自定义连接字符串

时间:2014-08-04 15:43:36

标签: c# web-config entity-framework-5

我需要在运行时指定DBContext的连接字符串。我是否需要指定web.config中存在的连接字符串(使用metadata = res:blah blah)?如果是这样,是否有办法应该这样做,因为只是粘贴在字符串中,因为它在Web配置中给出了“关键字不支持:'元数据'”错误。作为参考,连接字符串如下:

    <add name="EFEntities" connectionString="metadata=res://*/Models.MHFedmx.csdl|res://*/Models.MHFedmx.ssdl|res://*/Models.MHFedmx.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={IP ADDRESS}\;initial catalog={SOME DB};persist security info=True;user id={ID};password={PASSWORD};MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

var ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Models.MHFedmx.csdl|res://*/Models.MHFedmx.ssdl|res://*/Models.MHFedmx.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = "data source={IP ADDRESS};initial catalog={SOME DB};persist security info=True;user id={ID};password={PASSWORD};MultipleActiveResultSets=True;App=EntityFramework"

ecb.Connectionstring包含您正在寻找的连接字符串。