问题
Very mysterious issue here.
I have mdf-file in project with single table (double-clicking will show this):
CREATE TABLE [dbo].[Table] (
[Id] DATETIME NOT NULL,
[Version] NCHAR (20) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Then I add dbml (Linq-to-SQL), drag table there, add some code
partial class TestDataContext
{
public static string DatabaseFile { get; private set; }
public static string ConnectionString { get; private set; }
static TestDataContext()
{
DatabaseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.mdf");
ConnectionString = string.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename={0};Integrated Security=True", DatabaseFile);
}
public TestDataContext Attach()
{
Detach();
var context = new TestDataContext(ConnectionString);
// re-create database
if (!context.DatabaseExists() && !File.Exists(DatabaseFile))
context.CreateDatabase();
return context;
}
public static void Detach()
{
try
{
using (var master = new DataContext(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"))
{
master.ExecuteCommand(string.Format(@"ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", DatabaseFile));
master.ExecuteCommand(string.Format(@"exec sp_detach_db '{0}'", DatabaseFile));
}
}
catch { } // should be safe
}
public void Test()
{
var row = new Table() { Id = DateTime.Now, Version = "test1.0" };
Tables.InsertOnSubmit(row);
System.Threading.Thread.Sleep(5);
row = new Table() { Id = DateTime.Now, Version = "test1.1" };
Tables.InsertOnSubmit(row);
SubmitChanges();
}
}
It's all needed to detach database and to re-create database if file is deleted (maybe it's related to issue, see further). That new database is created near exe-file (don't mix it with one in project, used only to define structure and generate dmbl).
Now the problem: when I run application from within VS (F5), then this table is always blank. Even before calling Attach()
its content from previous run is erased ! It looks like if VS opens new mdf-file, find my table there (lol) and clears it!
Most confusing part: if compiled exe-file is running directly, then content persist between launches (as intended). As soon as I hit F5 in VS .. it become empty again.
Any idea?
I open that new mdf-file in VS "Database Explorer", to be able to see what is going on. Application adds some rows by calling Test()
and I see that in application and in explorer. Then application exits. Data still. Yes, I click refresh button, it is still. Then I hit F5 and before pressing button which call Attach()
switch to explorer and hit refresh there.. table is empty.
回答1:
Is the MDF file in your solution? Check the file properties for the 'Copy to Output Directory'. It should be on "Do not copy"
来源:https://stackoverflow.com/questions/25932031/mdf-table-content-is-deleted-when-starting-application-from-within-vs