I've got this code in my Winforms app to create a table in an existing database, (which I created by following what is written here):
private void CreateTables()
{
string connStr = @"Data Source=
(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|
\AYttFM.mdf;Integrated Security=True";
using (var connection = new
System.Data.SqlClient.SqlConnection(connStr))
{
try
{
connection.Open();
using (var command = connection.CreateCommand())
{
StringBuilder sb = new StringBuilder();
sb.Append("CREATE TABLE [dbo].[AssignmentHistory] ");
sb.Append("(");
sb.Append("[Id] INT NOT NULL PRIMARY KEY, ");
sb.Append("[WeekOfAssignment] DATE NOT NULL,");
sb.Append("[TalkType] INT NOT NULL,");
sb.Append("[StudentID_FK] INT NOT NULL, ");
sb.Append("[AssistantID_FK] INT NOT NULL, ");
sb.Append("[CounselPoint] INT NOT NULL");
sb.Append(")");
command.CommandText = sb.ToString();
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
It runs without complaint, but no table is created. Refreshing both the Data Connection and its Tables folder in Server Explorer in Visual Studio Community 2015 show no tables.
Am I missing something in the code above?
Note: I broke the connStr over several lines above for formatting purposes; in the actual code, connStr is all on one line.
I'm also not able to connect to the .mdf file via LINQPad, using the "Default LINQ to SQL" and SQL Server Provider and navigating to the .mdf file in my project (C:\AYttFMApp\AYttFMScheduler\AYttFMScheduler\AYttFM.mdf). It tells me there is a network error:
I get that whether I use the default Server ".\SQLEXPRESS" or whether I set it to my machine name (which is the only entry beneath "Servers" in Visual Studio's Server Explorer).
UPDATE
I rebooted my laptop, but it didn't help. Server Explorer's Data Connections show nothing, even after I refresh, and trying to add one, with my machine name as the Server Name (after all, that is what it says the Server is there in Server Explorer) and selecting the .mdf file gives me the same error when testing the connection as LINQPad does.
UPDATE 2
Curiouser and curiouser: Now when I run my app, when it gets to the Create Table code, I get an exception msg that says the AssignmentHistory table has already been created. Yet if I look at Server Explorer, although the database itself is back again, its Tables folder is still empty. How can the table both be there and not be there?
I'm still wondering if the properties set on the .mdf file are wrong; as I wrote in a comment below, the properties are all the defaults: "Copy to Output Directory" is set to "Copy Always" and "Build Action" is set to "Content" Should either of these be changed?