2

I was able to get somewhere using this article,

EF6 DBContext Dynamic Connection String

I have setup my partial class per the instructions above

public partial class PxxxxEntities
{
    private PxxxxEntities(string connectionString)
        : base(connectionString)
    {
    }

    public static PxxxxEntities ConnectToSqlServer(string host, string catalog, string user, string pass, bool winAuth)
    {
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
        {
            DataSource = host,
            InitialCatalog = catalog,
            PersistSecurityInfo = true,
            IntegratedSecurity = winAuth,
            MultipleActiveResultSets = true,

            UserID = user,
            Password = pass,
        };

        // assumes a connectionString name in .config of MyDbEntities
        var entityConnectionStringBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = sqlBuilder.ConnectionString,
            Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl",
        };

       return new PxxxxEntities(entityConnectionStringBuilder.ConnectionString);
    }
}

I am unable to initiate using the ConnectToSqlServer method though.

Attempt 1:

public PxxxxEntities database = new PxxxxEntities(PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true));     

'PxxxxEntities' does not contain a constructor that takes 1 argument

Attempt 2:

public PxxxxEntities database = new PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);  

The type name 'ConnectToSqlServer' does not exist in the type 'PxxxxEntities'

(Per Crowcoder Comment)

Attempt 3: Set the constructor to public

public PxxxxEntities database = new PxxxxEntities(PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true)); 

Cannot convert from model.PxxxxEntities to 'string'

(Per Nkosi) Attempt 4:

public PxxxxEntities database = PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);

Additional information: Unable to load the specified metadata

Had one minor change to make,

Update the Metadata in the method with the Metadata from the Web.Config. To resolve the Additional information: Unable to load the specified metadata

Success!!

Community
  • 1
  • 1
Terry
  • 1,621
  • 4
  • 25
  • 45

1 Answers1

2

The constructor of your DbContext is private and you have a static factory method ConnectToSqlServer but you are trying to call the constructor which is private. Nothing is wrong with the way you created the class. The problem is how you are trying to call the class.

public PxxxxEntities database = PxxxxEntities.ConnectToSqlServer
("server", "Catalogue","user","pass",true);
Nkosi
  • 235,767
  • 35
  • 427
  • 472