2

I have already checked other topics regarding the matter and tried some of the standard solutions but nothing seems to work. My DB is local and I'm trying to connect, it is already created and saved in the folder Helpers with the name of localDB.mdf My code is:

public static List<ChatMessages> GetFromDatabase(string query)
    {
        List<ChatMessages> ImportedFiles = new List<ChatMessages>();
        string sql = @"Data Source=|DataDirectory|\Helpers\localDB;AttachDbFilename=\Helpers\localDB.mdf;Integrated Security=True";
        SqlConnection connection = new SqlConnection(sql);
        try
        {
            connection.Open();
            var check = connection.State;
            SqlCommand cmd = new SqlCommand(query, connection);
            var rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                //stuff
            }
            connection.Close();
        }
        catch (Exception e) { MessageBox.Show("error: " + e); }
        var x = ImportedFiles;
        return ImportedFiles;
    }

Thanks for your time, Best regards

Ricardo
  • 409
  • 4
  • 22
  • @Win the thing is that inside the Visual Studio it runs smoothly but when I export it does in my Personal Computer but not in another computer – Ricardo Oct 19 '16 at 11:42
  • 1
    Make sure the correct Startup Project is chosen as well. – IronSean Jul 24 '18 at 17:06
  • **For Code Migrations** (`update-database` et al) [see this answer](https://stackoverflow.com/a/31266905/3258851). – Marc.2377 Jul 31 '18 at 21:17

1 Answers1

5

Already found an answer. After attempting a lot of hypothesis like the ones suggested by @Win I found the answer. So:

Project > Add New Data Source > Choose the local DB And the connection string suggested was:

@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\localDB.mdf; Integrated Security = True"

The difference is in the MSSQLLocalDB and in the use of the environment variable.

Ricardo
  • 409
  • 4
  • 22