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

3
  • @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 Commented Oct 19, 2016 at 11:42
  • 1
    Make sure the correct Startup Project is chosen as well. Commented Jul 24, 2018 at 17:06
  • For Code Migrations (update-database et al) see this answer. Commented Jul 31, 2018 at 21:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.