Entity Framework 4 Is it possible to read the connection string from another file, and not app.config?

I am new to EF using EF4 with First database and generation. I have to put the connection string in a different configuration than app.config.

How can i do this? How can I get around it?

I have a partial class MyTextContext and I have such a method

   public static string GenerateConnectionString()
  {
     SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

     // Set the properties for the data source.
     sqlBuilder.DataSource = dbServer;
     sqlBuilder.InitialCatalog = dbName;
     sqlBuilder.UserID = "YOUR_USERNAME";
     sqlBuilder.Password = "YOUR_PASSWORD";
     sqlBuilder.IntegratedSecurity = false;

     // Build the SqlConnection connection string.
     string providerString = sqlBuilder.ToString();

     // Initialize the EntityConnectionStringBuilder.
     var entityBuilder = new EntityConnectionStringBuilder();

     //Set the provider name.
     entityBuilder.Provider = "System.Data.SqlClient";

     // Set the provider-specific connection string.
     entityBuilder.ProviderConnectionString = providerString;

     // Set the Metadata location.
     entityBuilder.Metadata = @"res://*/myTestModel.csdl|
                            res://*/myTestModel.ssdl|
                            res://*/myTestModel.msl";


     return entityBuilder.ToString();
  }

I noticed that my EFModel.designer has this constructor:

    /// <summary>
    /// Initializes a new MyTestContext object using the connection string found in the 'MyTestContext' section of the application configuration file.
    /// </summary>
    public MyTestContext() : base("name=MyTestContext", "MyTestContext")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

    /// <summary>
    /// Initialize a new MyTestContext object.
    /// </summary>
    public MyTestContext(string connectionString) : base(connectionString, "MyTestContext")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

    /// <summary>
    /// Initialize a new MyTestContext object.
    /// </summary>
    public MyTestContext(EntityConnection connection) : base(connection, "MyTestContext")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

How can I use "GenerateConnectionString" instead of reading EF from app.config?

Thanks for any suggestions.

+3
source share
1 answer

Have you tried to use the second ctor overload?

public MyTestContext(string connectionString)

eg

var ctx = new MyTestContext(GenerateConnectionString());

From MSDN :

Entity , . ​​ connectionString ObjectContext.

, , , ( ).

, ( , ).

+4

Source: https://habr.com/ru/post/1774280/


All Articles