Click here to Skip to main content
15,888,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have some database and work with single mvc project and all of database are the same and all users register with this format( companyname/username)
when the user want login i get the databse and save in session
and when i want check the user is valid i get error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'


What I have tried:

login:

public ActionResult Login(LoginViewModel login, string ReturnUrl = "")
       {

           string input = login.username.Trim();

           int index = input.IndexOf("/");
           if (index > 0)
               input = input.Substring(0, index);





           if (input == "Pub")
           {
               Session["_DBNAME_"] = "database name";

           }


using (databaseEntities dbo = new databaseEntities(Session["_DBNAME_"].ToString()))
          {


------------------------------------------------------------
dbcontext:

  public partial class databaseEntities : DbContext
    {
      

        public databaseEntities(string companyName)
      
        {
            string connString = ConfigurationManager.ConnectionStrings["databaseEntities"].ConnectionString;
            connString = connString.Replace("_DBNAME_", companyName);
            this.Database.Connection.ConnectionString = connString;

get error here:


        }



--------------------------------------------

webconfig:

 <connectionStrings>

<add name="databaseEntities" connectionString="metadata=res://*/Models.databaseModel.csdl|res://*/Models.databaseModel.ssdl|res://*/Models.databaseModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=_DBNAME_;user id=sa;password=pwd;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

</connectionStrings>
Posted
Updated 19-Apr-20 0:48am

mohamad_ali wrote:

...i want switch between some data base with one connection string , only replce database name


So, create default-connection:
HTML
<connectionStrings>
    <add name="defaultconnection" providerName="System.Data.SqlClient"
        connectionString="Server=ServerName\InstanceName; Database=CompanyA;User Id=sa;Password=pwd;" />
</connectionStrings>



So, create connstring "on-demand"
C#
namespace YourNameSpaceHere
{
    public class YourEntity: DbContext
    {
        private string connstring = string.Empty;
        public YourEntity(string _companyName) : base()
        {

            //get default connection string 
            connstring = ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString;
            //returns:
            //"metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;data source=.;initial catalog=CompanyA;user id=sa;password=pwd;MultipleActiveResultSets=True;App=EntityFramework";
            Dictionary<string, string> connparts = GetConnParts(conn);
            connparts["initial catalog"] = _companyName;
            connstring = string.Join(";", connparts.Select(kvp=> $"{kvp.Key}={kvp.Value}"));
        }

	private Dictionary<string, string> GetConnParts(string sConnString)
	{
		return sConnString.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries)
			.Select(x=> new KeyValuePair<string, string>(x.Split('=')[0], x.Split('=')[1]))
			.ToDictionary(kvp=> kvp.Key, kvp=> kvp.Value);
	}


}


Note, that this method is not recommended!
 
Share this answer
 
v4
Comments
mohamad_ali 19-Apr-20 7:03am    
why, and which way is better?
Maciej Los 19-Apr-20 7:20am    
The best way is to define as many connection strings as many companies, then get connection string by company name ;) - solution #1
mohamad_ali 19-Apr-20 10:05am    
thnx for guidng me, but when the connection want opeen i got error

System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715'
Maciej Los 19-Apr-20 10:24am    
OK. My mistake, because you did not provide information about Code First. You have to use your connection string, instead of mine. Using GetConnParts method you can re-build connection string.
[EDIT]
See updated answer ;)
mohamad_ali 19-Apr-20 10:50am    
thnx alot ,the problem was solved
You're doing it wrong...

#1
If entity model is the same for each company, you have to define as many connections, as many companies (databases) you've got created:

XML
<connectionStrings>
    <add name="CompanyA" providerName="..." connectionString="..." />
    <add name="CompanyB" providerName="..." connectionString="..." />
</connectionStrings>


Your entity have to accept connection string as an input parameter:
C#
namespace YourNameSpaceHere
{
    public class YourEntity: DbContext
    {
        private string connstring = string.Empty;
        public YourEntity(string _companyName) : base()
        {

            //get connection string by company name
            connstring = ConfigurationManager.ConnectionStrings[_companyName].ConnectionString;
        }


}


#2
If entity model between companies is different, you have to define different entity for each company
C#
public Company1Context()
            : base("Company1") // connection string key
        {
            //define options here
        }

public Company2Context()
            : base("Company2") // connection string key
        {
            //define options here
        }
 
Share this answer
 
v3
Comments
mohamad_ali 19-Apr-20 5:54am    
thnx for answer,but i want switch between some data base with one connection string , only replce database name
Maciej Los 19-Apr-20 6:48am    
See, solution #2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900