【发布时间】:2016-09-13 21:45:59
【问题描述】:
我知道有人问过here 一个非常相似的问题,但答案对我没有帮助。
我正在使用带有 Oracle.ManagerDataAccess.Client 的 Entity Framework 6。
如果我在 app.config 中定义连接字符串,则连接有效。 如果我在代码中指定相同的连接字符串,则会收到错误
The value's length for key 'data source' exceeds it's limit of '128'.
这是正确的。
这是我的连接字符串(删除了一些名称):
"User Id=xxxxxxxxxxx;Password=xxxx;Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = (PROTOCOL = TCP)(HOST = VS-ORACLE.xxxxxxx.de)(PORT = 1521) ) ) ( CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = orcl.xxxxxxxx.de) ) )"
我知道有一堆空格可以删除,但我仍然不会让字符串低于 128 个字符。
连接字符串在app.config中时如何工作,而在代码中时却不行?
通过将一些参数卸载到另一个字符串,我可以使用任何技巧吗?
我已经在使用 DBConfiguration 对象。有没有办法在那个对象中设置一些参数?
如果我使用完整的 oracle 客户端,我想我可以引用文件 tnsnames.ora 中的配置,但是如果我们可以在没有完整客户端的情况下与 oracle 数据库通信,那将是一个很大的好处。
更新
这就是 app.config 中连接字符串的样子
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=xxxxxxxxxxx;Password=xxxx;Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = (PROTOCOL = TCP)(HOST = VS-ORACLE.xxxxxxxx.de)(PORT = 1521) ) ) ( CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = orcl.xxxxxxxx.de) ) )" />
</connectionStrings>
在代码中我定义了上下文类如下:
[DbConfigurationType(typeof(OracleDBConfiguration))]
public class GlobalAttributeContext : DbContext
{
public DbSet<GlobalAttribute> GlobalAttributes { get; set; }
static GlobalAttributeContext()
{
Database.SetInitializer<GlobalAttributeContext>(null);
}
public GlobalAttributeContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
public GlobalAttributeContext() : this ( "Name=OracleDbContext" )
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// We have to pass the schema name into the configuration. (Is there a better way?)
modelBuilder.Configurations.Add(new GlobalAttribute_Config_Oracle("SchemaName")) ;
}
}
我已经定义了一个 DbConfiguration 类如下:
class OracleDBConfiguration : DbConfiguration
{
public OracleDBConfiguration()
{
this.SetDefaultConnectionFactory ( new System.Data.Entity.Infrastructure.LocalDbConnectionFactory("v12.0") ) ;
this.SetProviderServices ( "Oracle.ManagedDataAccess.Client", Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices.Instance ) ;
this.SetProviderFactory ( "Oracle.ManagedDataAccess.Client", Oracle.ManagedDataAccess.Client.OracleClientFactory.Instance ) ;
}
}
最后,我创建了这样的上下文
string ConnectionString = "User Id=xxxxxxxxxxx;Password=xxxx;Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = (PROTOCOL = TCP)(HOST = VS-ORACLE.xxxxxxxx.de)(PORT = 1521) ) ) ( CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = orcl.xxxxxxx.de) ) )" ;
using (var ctx = new GlobalAttributeContext(ConnectionString))
{
var globalAttributes = ctx.GlobalAttributes.ToList() ;
foreach ( GlobalAttribute ga in globalAttributes )
{
Console.WriteLine ( "Name: {0}, Value: {1}", ga.Attribute, ga.Value ) ;
}
}
这两种方法中使用的连接字符串是相同的。
【问题讨论】:
-
如何在代码中设置连接字符串?我以前从未见过有关连接字符串的错误。
-
我添加了更多信息。
标签: c# oracle ef-code-first entity-framework-6 connection-string