7

Here is what i have so far :

    <add name="gymEntities1" connectionString="metadata=res://*/DateModel.csdl|res://*/DateModel.ssdl|res://*/DateModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=gym;user id=sa;password=xxxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

it works on my LocalHost Database, and I can load my Data from it. however, I have a server, installed sqlserver with my database on that, basicaly when i change my sqlcommands connecting string this work but in some part of my program I used entity framework and have no idea how to change it connecting string, with some posts in stackoverflow I change that to

    <add name="gymEntities2" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:46.105.124.144;initial catalog = gym ;User ID=sa;Password=xxxx&quot;" providerName="System.Data.EntityClient" />

but it still read datas from my localhost and not connect to my server. I don't know how when i change this connecting string to my server it still read data from my localhost database.

what is the best way to change connecting string from App.Config?

Falco Alexander
  • 3,092
  • 2
  • 20
  • 39
Reza Pak
  • 129
  • 2
  • 9

4 Answers4

3

First Possible Issue:

It is less likely since other people suggested to you.But, it is possible that you are missing a connection string in one of your web.config or app.config. It is a good habit to copy your string to every project. Example. I have 3 different projects in my solution (Library, WCF, WPF). I copied the following connection string to each project (One sample for Local SQL Server and another for Azure):

<connectionStrings>
    <add name="LocalSQLServerSample.CodeREDEntities" connectionString="metadata=res://*/CodeRED.csdl|res://*/CodeRED.ssdl|res://*/CodeRED.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MachineName\ServerName;initial catalog=CodeRED;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="AzureSQLServerSample.CodeREDEntities" connectionString="metadata=res://*/CodeRED.csdl|res://*/CodeRED.ssdl|res://*/CodeRED.msl;provider=System.Data.SqlClient;provider connection string='data source=azureservername.database.windows.net;initial catalog=&quot;CodeRED&quot;;persist security info=True;user id=CodeRED;password=R%Chd$g*VHs28eEr;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>

Second possible issue:

You have mentioned that you are using entity framework. Are you using ObjectContext to access it? If yes, I have the method below to call it every time I want to access any database:

From sample above: name="LocalSQLServerSample.CodeREDEntities"

_containerName is CodeREDEntities (The same for all my connections). environment is to determine which database you are connecting to. For example, in the above connection sample, I have LocalSQLServerSample and AzureSQLServerSample and I usually have something like PRODUCTION, DEVELOPMENT, TESTING....

    public static ObjectContext getObjectContext(string environment, bool isReadOnly)
    {
        environment = environment == null ? "" : environment.Trim();
        environment = environment.Length == 0 ? "" : (environment + ".");

        ObjectContext objectContext = new ObjectContext(
                ConfigurationManager.ConnectionStrings[environment + _containerName].ToString());
        objectContext.DefaultContainerName = _containerName;
        objectContext.CommandTimeout = 0;

        objectContext.ContextOptions.ProxyCreationEnabled = !isReadOnly;

        return objectContext;
    }

Sample of how to use it:

Common is a common class that I use to store shared information such as getting common error format used for Common.getInnerExceptionMessage.

Also, you don't have to always pass environment, you can store it as a constant to be able to call it such as (I always pass it to be able to mix connection when I need to for specific calls): You can modify connection from anywhere by changing _selectedEnvironment if you do not wish to pass it everywhere.

    public const string _ENVIRONMENT_DEVELOPMENT = "LocalSQLServerSample";
    public const string _ENVIRONMENT_PRODUCTION = "AzureSQLServerSample";
    public static string _selectedEnvironment = _ENVIRONMENT_PRODUCTION;

Sample of getting item based on id:

Note: User is a class generated by entity framework from database.

    public UsersDataGrid GetItem(string environment, long id)
    {
        ObjectContext objectContext = Common.getObjectContext(environment, false);

        try
        {
            var item = objectContext.CreateObjectSet<User>()
                .Where(W => W.ID == id)
                .Select(S => new UsersDataGrid()
                {
                    Active = S.Active,
                    ID = S.ID,
                    Unique_ID = S.Unique_ID,
                    First_Name = S.First_Name.ToUpper(),
                    Last_Name = S.Last_Name.ToUpper(),
                    Email = S.Email,
                    School = S.School.Title.ToUpper(),
                    Gender = S.Gender.Title.ToUpper(),
                    TShirt_Size = S.TShirt_Size.Title.ToUpper(),
                    GUID = S.GUID + "",
                    Note = S.Note,
                    Machine_User = S.Machine_User,
                    Machine_Name = S.Machine_Name,
                    Created_On = S.Created_On,
                    Last_Updated_On = S.Updated_On
                }).FirstOrDefault();

            return item;
        }
        catch (Exception exception)
        {
            return new UsersDataGrid()
            {
                Note = ("Service Error: " +
                Common.getInnerExceptionMessage(exception))
            };
        }
    }

2nd Sample: Updating a user:

Note: Common.CopyValuesFromSourceToDestinationForUpdate is only a generalized method copying items from item object to entityItem, instead you can copy values normally such as entityItem.ID = item.ID and so on...

    public Result Update(string environment, User item)
    {
        ObjectContext objectContext = WCF_Service_Library.Classes.Common.getObjectContext(environment, false);

        try
        {
            var entityItem = objectContext.CreateObjectSet<User>()
                .AsEnumerable().Where(Item => Item.ID == item.ID).ToList().FirstOrDefault();

            if (entityItem == null)
                return new Result("Item does NOT exist in the database!");

            entityItem = Common.CopyValuesFromSourceToDestinationForUpdate(item, entityItem) as User;

            objectContext.SaveChanges();

            return new Result(entityItem.ID);
        }
        catch (Exception exception)
        {
            return new Result("Service Error: " + Common.getInnerExceptionMessage(exception));
        }
    }

Third issue (it does not look like it, but you may encounter it):

If you publish your app and ONLY sign your WPF project, you will not get error during publishing, but you may not be able to connect to the database. You must sign all your projects in your solution.

Hopefully this help you with your problem

  • Thx For Your UseFull Method. i have a little qustion in here, my problem sloved but do u think which one of the sqlcommands or EntityFramwork methods are have more speed than each? Aculy when i run my program everything is ok expect my program loading data speed from server, someone tell me that u can use Await, Task.... Whats ur best idea? – Reza Pak Nov 02 '18 at 22:52
  • You are very welcome. I don't think that I am the best person to help you with this question. It depends on what are trying to do, there are several different solutions for different situations. I like using await and Task, but not necessarily for speed. Most of the time I use it to be able to have responsive UI or being able to show updates on requested data such as if I am saving 1000 new records. Also, in my opinion, you should avoid getting all the data every time and only get the records that you need. – Mohammed Alshair Nov 03 '18 at 01:03
  • Continuing. For example: I don't enable editing on datagrid. I always make it read only and deal with each update/new record separately, this improves speed drastically especially when you have a lot of rows. Also, they way you query it is important depending on some situation. For example if you want to get count, you don't want to get it after .ToList().Count, you want use it early on in the query .Count to the count from the translated SQL query. Filtering the data (.Where clause) is very important to speed query. You are very welcome to give me specific scenario and I will try to help. – Mohammed Alshair Nov 03 '18 at 01:07
  • i cant send my qustion in form :D sorry for that and i make a new post with my qustion , cheak out that . did u know why it dosent work yet? it will be deleted after you answer that. – Reza Pak Nov 03 '18 at 01:48
  • if u can correct code , correct code that and re-post again . after copy i will delete there. – Reza Pak Nov 03 '18 at 01:49
  • I know comments gets deleted. You can post your question in new post and comment here with the link so that I know you have posted and I will try to help you. Good Luck! – Mohammed Alshair Nov 03 '18 at 02:57
  • can u cheak out it ? https://stackoverflow.com/questions/53129725/how-to-load-new-page-with-await-method – Reza Pak Nov 03 '18 at 08:48
1

Check the WebConfig of your startup project. Entity framework reads ConnnectionString from AppConfig when you run Update Model From Db operation .

But in runtime it reads ConnnectionString from WebConfig in your Startup project

  • Does WPF application use `WebConfig` file? – Miamy Nov 02 '18 at 12:48
  • I dont think so – Reza Pak Nov 02 '18 at 13:52
  • i searched in my project but WebConfig isnt exist. – Reza Pak Nov 02 '18 at 14:01
  • 1
    No, it does not have WebConfig... It has app.config... your connection should be there. But your problem is more likely is in the DefaultContainerName in your ObjectContext because probably you created one entity (first connection), then you are trying to use the same created entity with different connection. Check my post below for more details. Hopefully this help you. Good Luck! – Mohammed Alshair Nov 02 '18 at 19:12
1
I hope it is use for you
Add this for App.Config files


<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping;
       Integrated Security=True"; providerName="System.Data.SqlClient" />
</connectionStrings>
0

This connection string must be work:

   <add name="Name"
   connectionString="metadata=<Conceptual Model>|<Store Model>|<Mapping Model>;
   provider=<Underlying Connection Provider>;
   provider connection string=&quot;<Underlying ConnectionString>&quot;" 
   providerName="System.Data.EntityClient"/>

If you have any problems with writing connection string, you can use following code on the page.

PWND
  • 409
  • 3
  • 11