简体   繁体   English

在C#中使用.mdf数据库的正确方法是什么?

[英]What is the correct way to work with an .mdf database in C#?

I've had quite a bit of difficulty with this. 我在这方面遇到了很多困难。 I want to create a database and a table underneath, which I assume I just use the Data Sources and Add New Data Source. 我想在下面创建一个数据库和一个表,假设我只是使用数据源并添加新数据源。

But then things get crazy. 但是后来事情变得疯狂了。 I want to have a data set in memory, so I drag the Table to the Windows form, which creates a DataGridView and a navigation bar. 我想在内存中设置一个数据集,所以我将Table拖到Windows窗体,该窗体创建一个DataGridView和一个导航栏。

But I don't need any of that crap. 但我不需要任何废话。 And I don't want to bind directly to a particular control such as a Text box. 而且我不想直接绑定到诸如文本框之类的特定控件。 What if I just want to say, press a button, and have the program load data from a file and write it to the Database? 如果我只是想说,按一下按钮,让程序从文件中加载数据并将其写入数据库该怎么办? Should be straightforward right? 应该简单明了吧?

Well, that brings me to the next issue - when I see the database (.MDF) file in my Solution, In Properties I have the choices Copy Always, Copy if Newer, and Never copy. 好吧,这使我想到下一个问题-当我在解决方案中看到数据库(.MDF)文件时,在“属性”中,选择“始终复制”,“如果较新则复制”和“从不复制”。

Tried all three. 尝试了所有三个。 Copy always always seems to overwrite the changes? 复制总是总是似乎会覆盖更改? Copy it newer seems to do the same thing. 复制它似乎做同样的事情。 And if I say Copy Never I get an error about a database with that name already existing? 如果我说“从不复制”,那么我会收到有关该名称已经存在的数据库的错误消息? What even good is "Copy Always"??? “始终复制”甚至有什么好处呢???? " Why yes. All those changes I made while running my application In would like to all disappear so I can't test it." “为什么呢?我在运行应用程序In时所做的所有更改都希望全部消失,因此我无法对其进行测试。”

What is the correct way to do this stuff? 做这个东西的正确方法是什么? This is just nuts that I'm pulling my hair out. 这只是胡说八道,我正在拔头发。

The best way is to stop fiddling around with free-floating .mdf files altogether. 最好的方法是完全停止自由浮动的.mdf文件。

Put the database on the server (where it belongs) and let SQL Server handle all the details about file handling. 将数据库放在服务器 (它所属的服务器 )上,然后让SQL Server处理有关文件处理的所有详细信息。

Just create the database on the server , connect to the server using server/instance name and database name 只需在服务器上创建数据库,然后使用服务器/实例名称和数据库名称连接到服务器

server=myhonker\SQL2012;database=TestDB;Integrated Security=SSPI;

that's all there is! 这就是全部! No more messing around with copying files around, inserting into the wrong file and so forth.... 无需再四处寻找文件复制,插入错误的文件等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM