Как создать бд в visual studio

от admin

Создаем проект базы данных в Visual Studio 2019

В настоящее время базы данных (БД) являются проблемой для разработчиков, и это одна из самых сложных задач в любом проекте ПО для управления изменениями БД и синхронизации этих изменений. Для решения этой проблемы в Visual Studio имеются проекты баз данных SQL. Можно с легкостью разрабатывать, управлять, сравнивать и развертывать изменения базы данных с помощью Visual Studio.

А также можем отслеживать изменения всех объектов БД через систему контроля версий. Visual Studio Database Project предоставляет гибкие возможности для создания нового проекта базы данных из существующей БД с помощью нажатия на кнопку или возможность создания проекта базы данных с нуля.

Итак, поехали

Запускаем Visual Studio 2019, выбираем Create a new project, потом выбираем SQL Server Database Project.

Введем название базы данных и выберем место расположения файла.

После чего щелкаем по кнопке Create. А теперь правой кнопкой мыши щелкаем по проекту SampleDB и из появившейся меню выбираем Add > Table.

Присваиваем имя таблице – “Student” и щелкаем по кнопке Add.

После того, как добавили таблицу, появится окно конструктора таблицы. Здесь мы можем добавлять столбцы с типом данных.

Добавим несколько столбцов в эту таблицу. Мы увидим, что сгенерируется скрипт в нижней части окна и сохраняется схема таблицы.

Теперь пора опубликовать базу данных в SQL Server

Щелкаем правой кнопкой мыши в окне Solution Explorer по проекту базы данных. В появившемся меню выбираем Properties. В параметрах проекта выбираем версию SQL Server.

Кроме того, мы можем изменять подключение по умолчанию на вкладке Debug Щелкаем по кнопке Edit.

Изменяем свойства соединения в соответствии с параметрами ПК. Введем имя сервера, имя пользователя, пароль и выберем базу данных. Потом щелкаем по кнопке OK. Если есть проверка подлинности Windows, то не нужно указывать имя пользователя и пароль. Нам нужно только имя сервера и база данных.

Не забываем сохранять все изменения. А теперь щелкаем правой кнопкой мыши на проекте БД и выбираем Publish… Редактируем настройки Target Database.

Введем свойства подключения, такие как – если это проверка подлинности SQL Server, то указываем имя сервера, имя пользователя, пароль и выбираем базу; а если это аутентификация Windows, то указываем имя сервера и базу данных.

После чего мы жмем на кнопку Publish. Немного подождем, пока БД не будет опубликована.

Теперь запускаем SQL Server Management Studio и проверяем, есть ли база данных SampleDB или нет.

Вывод

В этой статье мы узнали, как создать проект базы данных в Visual Studio 2019 и публиковать ту же БД в SQL Server 2017.

Create Your First Visual Studio Database Project

Databases should be under source control and have the ability for CI/CD just like application code. Visual Studio gives you this capability. Here, we will show you how to get your databases into a Visual Studio Database Project.

Download Visual Studio

If you don’t have Visual Studio, download it from here.

During the installation, you will be asked to choose your Workload(s). You need to check Data storage and processing. You can also check others if you want to give them a try or add them later.

Create a New Project

Launch Visual Studio and select Create a new project.

Search for database and select SQL Server Database Project. Click Next.

Enter the name of the project. The Solution Name defaults to Project Name. For this example, we will use Adventure Works and make the Solution Name generic for when we add additional databases down the road. Set the location to your preference.

When Visual Studio opens, you will see the Solution Explorer window. The Solution will have one project, Adventure Works. Right-click on the project and select Import, then Database.

Enter the connection information and uncheck Import referenced logins. Logins will have different permissions in UAT and Production and we don’t want to increase or decrease permissions unintentionally.

After the Import is complete, you will see folders for each schema and a few others for administration. Example:

Managing Development

You can make changes within Visual Studio or in the database and sync the changes. If you are working with tables or making global searches or changes, I would start with Visual Studio. For code development, you may prefer to work in the database and sync views, stored procedures, etc., when you have working code.

Here is an example of editing a table in Visual Studio. It has a Design pane and a T-SQL pane. Updates in one pane are automatically reflected in the other pane. So you work where it is more comfortable.

After you do some development in the database, you must pull your changes into Visual Studio. I created a stored procedure template to illustrate the process.

To pull the changes into Visual Studio, go to Tools, SQL Server, New Schema Comparison.

Click on the Select Source dropdown and enter your database connection. After you create a new connection it will be saved for future use.

For the target, we will select the project.

After the source and targets are entered, click Compare.

When the comparison is done, and we go into the Results pane, we will see a list of Add, Changed, and Deleted objects between the two. The Object Definitions pane will show the source code differences. If you split the window, you can see both and scroll through the objects that will be updated.

If you do not want to push any object to the target, you can uncheck the box next to the plus sign. Group highlighting and excluding works as expected.

We can now click Update to push the changes to our project. Confirm the update and the changes are applied to your project.

Publish Changes to a Database

The Publish process will do a Build of the project to validate and create a dacpac (a self-contained Data-Tier Application package used for deployments) file for processing.

The Build process will highlight warnings and errors. You can also suppress warnings. Most warnings are based on Best Practices as determined by Microsoft. Errors must be fixed because they will not execute. To show a warning, I changed the case of a column in a view. Let’s see the Build process.

Right-click on the Project and select Build.

The output shows the build succeeded, but there were warnings.

If you want to clean up the code, go to the error pane and double-click the warning. The source file will open in the editor and highlight the location of the warning.

You can suppress these warnings under Project Properties. Enter the warning number without the SQL prefix in the Suppression box.

To push the changes to a database, right-click the project and select publish. For this example, we will publish to a QA database that was created on the server and does not contain any object yet.

After we enter in the connection, we can generate the script to preview what will be happening. This is also helpful in debugging when this gets complicated and you may need pre and post-deployment scripts. For a simple change, we can click publish.

Name already in use

visualstudio-docs / docs / data-tools / create-a-sql-database-by-using-a-designer.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Create a database and add tables in Visual Studio

You can use Visual Studio to create and update a local database file in SQL Server Express LocalDB. You can also create a database by executing Transact-SQL statements in the SQL Server Object Explorer tool window in Visual Studio. In this topic, you create an .mdf file and add tables and keys by using the Table Designer.

To complete this walkthrough, you need the .NET desktop development and Data storage and processing workloads installed in Visual Studio. To install them, open Visual Studio Installer and choose Modify (or More > Modify) next to the version of Visual Studio you want to modify.

[!NOTE] The procedures in this article apply only to .NET Framework Windows Forms projects, not to .NET Core Windows Forms projects.

Create a project and a local database file

Create a new Windows Forms App (.NET Framework) project and name it SampleDatabaseWalkthrough.

On the menu bar, select Project > Add New Item. If you see a small dialog box with a box for a filename, choose Show All Templates.

In the list of item templates, scroll down and select Service-based Database.

. moniker range=»>=vs-2022″ Add New item > Service-based database . moniker-end . moniker range=»<=vs-2019″ Add New item > Service-based database . moniker-end

Name the database SampleDatabase.mdf, and then click Add.

Add a data source

If the Data Sources window isn’t open, open it by pressing Shift+Alt+D or selecting View > Other Windows > Data Sources on the menu bar.

In the Data Sources window, select Add New Data Source.

Add new data source in Visual Studio

. moniker range=»>=vs-2022″ . moniker-end . moniker range=»<=vs-2019″ alt=»Add new data source in Visual Studio» width=»» /> . moniker-end

The Data Source Configuration Wizard opens.

On the Choose a Data Source Type page, choose Database and then choose Next.

On the Choose a Database Model page, choose Next to accept the default (Dataset).

On the Choose Your Data Connection page, select the SampleDatabase.mdf file in the drop-down list, and then choose Next.

On the Save the Connection String to the Application Configuration File page, choose Next.

On the Choose your Database Objects page, you see a message that says the database doesn’t contain any objects. Choose Finish.

View properties of the data connection

You can view the connection string for the SampleDatabase.mdf file by opening the Properties window of the data connection:

Select View > SQL Server Object Explorer to open the SQL Server Object Explorer window. Expand (localdb)\MSSQLLocalDB > Databases, and then right-click on SampleDatabase.mdf (it might be listed as a full path) and select Properties.

Alternatively, you can select View > Server Explorer, if that window isn’t already open. Open the Properties window by expanding the Data Connections node, right-clicking on SampleDatabase.mdf, and then selecting Properties.

[!TIP] If you can’t expand the Data Connections node, or the SampleDatabase.mdf connection is not listed, select the Connect to Database button in the Server Explorer toolbar. In the Add Connection dialog box, make sure that Microsoft SQL Server Database File is selected under Data source, and then browse to and select the SampleDatabase.mdf file. Finish adding the connection by selecting OK.

Create tables and keys by using Table Designer

In this section, you create two tables, a primary key in each table, and a few rows of sample data. you also create a foreign key to specify how records in one table correspond to records in the other table.

Create the Customers table

In Server Explorer or SQL Server Object Browser, expand the Data Connections node, and then expand the SampleDatabase.mdf node.

Right-click on Tables and select Add New Table.

The Table Designer opens and shows a grid with one default row, which represents a single column in the table that you’re creating. By adding rows to the grid, you add columns in the table.

In the grid, add a row for each of the following entries:

Right-click on the CustomerID row, and then select Set Primary Key.

Right-click on the default row ( Id ), and then select Delete.

Name the Customers table by updating the first line in the script pane to match the following sample:

Add an index constraint to the Customers table. Add a comma at the end of the Phone line, then add the following sample before the closing parenthesis:

You should see something like this:

Table Designer with Customers table

. moniker range=»>=vs-2022″ . moniker-end . moniker range=»<=vs-2019″ alt=»Table Designer with Customers table» width=»» /> . moniker-end

In the upper-left corner of Table Designer, select Update, or press Shift+Alt+U.

In the Preview Database Updates dialog box, select Update Database.

The Customers table is created in the local database file.

Create the Orders table

Add another table, and then add a row for each entry in the following table:

Set OrderID as the primary key, and then delete the default row.

Name the Orders table by updating the first line in the script pane to match the following sample:

Add an index constraint to the Customers table. Add a comma at the end of the OrderQuantity line, then add the following sample before the closing parenthesis:

In the upper-left corner of the Table Designer, select Update, or press Shift+Alt+U..

In the Preview Database Updates dialog box, select Update Database.

The Orders table is created in the local database file. If you expand the Tables node in Server Explorer, you see the two tables:

Tables node expanded in Server Explorer

. moniker range=»>=vs-2022″ . moniker-end . moniker range=»<=vs-2019″ alt=»Tables node expanded in Server Explorer» width=»» /> . moniker-end

If you don’t see it, hit the Refresh toolbar button.

Create a foreign key

In the context pane on the right side of the Table Designer grid for the Orders table, right-click on Foreign Keys and select Add New Foreign Key.

Add a foreign key in Table Designer in Visual Studio

. moniker range=»>=vs-2022″ . moniker-end . moniker range=»<=vs-2019″ alt=»Add a foreign key in Table Designer in Visual Studio» width=»» /> . moniker-end

In the text box that appears, replace the text ToTable with Customers.

In the T-SQL pane, update the last line to match the following sample:

In the upper-left corner of the Table Designer, select Update (Shift+Alt+U).

In the Preview Database Updates dialog box, select Update Database.

The foreign key is created.

Populate the tables with data

In Server Explorer or SQL Server Object Explorer, expand the node for the sample database.

Open the shortcut menu for the Tables node, select Refresh, and then expand the Tables node.

Open the shortcut menu for the Customers table, and then select Show Table Data or View Data.

Add whatever data you want for some customers.

You can specify any five characters you want as the customer IDs, but choose at least one that you can remember for use later in this procedure.

Open the shortcut menu for the Orders table, and then select Show Table Data or View Data.

Add data for some orders. As you enter each row, it’s saved in the database.

[!IMPORTANT] Make sure that all order IDs and order quantities are integers and that each customer ID matches a value that you specified in the CustomerID column of the Customers table.

Congratulations! You now know how to create tables, link them with a foreign key, and add data.

Пример создания локальной базы данных Microsoft SQL Server в MS Visual Studio

В данной теме показано решение задачи создания базы данных типа SQL Server с помощью MS Visual Studio . Рассматриваются следующие вопросы:

  • работа с окном Server Explorer в MS Visual Studio ;
  • создание локальной базы данных типа SQL Server Database ;
  • создание таблиц в базе данных;
  • редактирование структур таблиц;
  • связывание таблиц базы данных между собой;
  • внесение данных в таблицы средствами MS Visual Studio .

Содержание

  • Условие задачи
  • Выполнение
    • 1. Загрузить MS Visual Studio .
    • 2. Активировать окно Server Explorer .
    • 3. Создание базы данных “ Education ”.
    • 4. Объекты базы данных Education .
    • 5. Создание таблицы Student .
    • 6. Создание таблицы Session .
    • 7. Редактирование структуры таблиц.
    • 8. Установление связей между таблицами.
    • 9. Ввод данных в таблицы.

    Поиск на других ресурсах:

    Условие задачи

    Используя средства MS Visual Studio создать базу данных типа MS SQL Server с именем Education. База данных содержит две таблицы Student и Session. Таблицы между собой связаны по некоторыму полю.

    Структура первой таблицы «Student».

    02_02_00_014_table01_r

    Структура второй таблицы “ Session ”.

    02_02_00_014_table02_r

    Выполнение

    1. Загрузить MS Visual Studio .
    2. Активировать окно Server Explorer .

    Для работы с базами данных корпорация Microsoft предлагает облегченный сервер баз данных Microsoft SQL Server . Существуют разные версии Microsoft SQL Server , например: Microsoft SQL Server 2005 , Microsoft SQL Server 2008 , Microsoft SQL Server 2014 и прочие версии.

    Загрузить эти версии можно с сайта Microsoft www.msdn.com.

    Этот сервер отлично подходит для работы с базами данных. Он бесплатен и имеет графический интерфейс для создания и администрирования баз данных с помощью SQL Server Management Tool .

    Прежде всего, перед созданием базы данных, нужно активировать утилиту Server Explorer . Для этого, в MS Visual Studio нужно вызвать (рис. 1)

    База данных Server Explorer команда

    Рис. 1. Вызов Server Explorer

    После вызова окно Server Explorer будет иметь приблизительный вид, как показано на рисунке 2.

    База данных окно Server Explorer

    Рис. 2. Окно Server Explorer

    3. Создание базы данных “Education”.

    Чтобы создать новую базу данных, базирующуюся на поставщике данных Microsoft SQL Server , нужно кликнуть на узле Data Connections, а потом выбрать “ Create New SQL Server Database … ” (рис. 3).

    база данных SQL Server команда

    Рис. 3. Вызов команды создания базы данных SQL Server

    В результате откроется окно « Create New SQL Server Database » (рис. 4).

    В окне (в поле «Server Name») указывается имя локального сервера, установленного на вашем компьютере. В нашем случае это имя “ SQLEXPRESS ”.

    В поле « New database name: » указывается имя создаваемой базы данных. В нашем случае это имя Education.

    Опцию Use Windows Autentification нужно оставить без изменений и нажать кнопку OK .

    SQL Server 2008 Express команда создание

    Рис. 4. Создание новой базы данных SQL Server 2008 Express с помощью MS Visual Studio 2010

    После выполненных действий, окно Server Explorer примет вид, как показано на рисунке 5. Как видно из рисунка 5, в список имеющихся баз данных добавлена база данных Education с именем

    Server Explorer база данных рисунок

    Рис. 5. Окно Server Explorer после добавления базы данных Education

    4. Объекты базы данных Education.

    Если развернуть базу данных Education (знак « + »), то можно увидеть список из следующих основных объектов:

    • Database Diagrams – диаграммы базы данных. Диаграммы показывают связи между таблицами базы данных, отношения между полями разных таблиц и т.п.;
    • Tables – таблицы, в которых помещаются данные базы данных;
    • Views – представления. Отличие между представлениями и таблицами состоит в том, что таблицы баз данных содержат данные, а представления данных не содержат их, а содержимое выбирается из других таблиц или представлений;
    • Stored procedures – хранимые процедуры. Они представляют собою группу связанных операторов на языке SQL, что обеспечивает дополнительную гибкость при работе с базой данных.
    5. Создание таблицы Student.

    На данный момент база данных Education абсолютно пустая и не содержит никаких объектов (таблиц, сохраненных процедур, представлений и т.д.).

    Чтобы создать таблицу, нужно вызвать контекстное меню (клик правой кнопкой мышки) и выбрать команду “ Add New Table ” (рисунок 6).

    база данных таблица создать

    Рис. 6. Команда добавления новой таблицы

    Существует и другой вариант добавления таблицы базы данных с помощью команд меню Data:

     таблица создание рисунок

    Рис. 7. Альтернативный вариант добавления новой таблицы

    В результате откроется окно добавления таблицы, которое содержит три столбца (рисунок 8). В первом столбце “Column Name” нужно ввести название соответствующего поля таблицы базы данных. Во втором столбце “Data Type” нужно ввести тип данных этого поля. В третьем столбце “ Allow Nulls ”указывается опция о возможности отсутствия данных в поле.

    SQL Server таблица создание

    Рис. 8. Окно создания новой таблицы

    С помощью редактора таблиц нужно сформировать таблицу Student как изображено на рисунке 9. Имя таблицы нужно задать при ее закрытии.

    В редакторе таблиц можно задавать свойства полей в окне Column Properties. Для того, чтобы задать длину строки (nvchar) в символах, в окне Column Properties есть свойство Length. По умолчанию значения этого свойства равно 10.

    SQL Server таблица проектирование рисунок

    Рис. 9. Таблица Student

    Следующим шагом нужно задать ключевое поле. Это осуществляется вызовом команды “ Set Primary Key ” из контекстного меню поля Num_book. С помощью ключевого поля будут установлены связи между таблицами. В нашем случае ключевым полем есть номер зачетной книжки.

    таблица SQL Server ключевое поле

    Рис. 10. Задание ключевого поля

    После установки первичного ключа окно таблицы будет иметь вид как изображено на рисунке 11.

    SQL Server таблица формирование

    Рис. 11. Таблица Student после окончательного формирования

    Теперь можно закрыть таблицу. В окне сохранения таблицы нужно задать ее имя – Student (рис. 12).

    таблица имя SQL Server ввод

    Рис. 12. Ввод имени таблицы Student

    6. Создание таблицы Session.

    По образцу создания таблицы Student создается таблица Session.

    На рисунке 13 изображен вид таблицы Session после окончательного формирования. Первичный ключ ( Primary Key ) устанавливается в поле Num_book. Имя таблицы задается Session.

    таблица формирование SQL Server

    Рис. 13. Таблица Session

    После выполненных действий, в окне Server Explorer будут отображаться две таблицы Student и Session.

    Таким образом, в базу данных можно добавлять любое количество таблиц.

    7. Редактирование структуры таблиц.

    Бывают случаи, когда нужно изменить структуру таблицы базы данных.

    Для того, чтобы вносить изменения в таблицы базы данных в MS Visual Studio, сначала нужно снять опцию “Prevent Saving changes that require table re-creation ” как показано на рисунке 14. Иначе, MS Visual Studio будет блокировать внесения изменений в ранее созданную таблицу. Окно Options, показанное на рисунке 14 вызывается из меню Tools в такой последовательности:

    SQL Server изменения опция

    Рис. 14. Опция “ Prevent Saving changes that require table re-creation ”

    После настройки можно изменять структуру таблицы. Для этого используется команда “ Open Table Definition ” (рисунок 15) из контекстного меню, которая вызывается для выбранной таблицы (правый клик мышкой).

    SQL Server команда рисунок

    Рис. 15. Вызов команды “ Open Table Definition ”

    Также эта команда размещается в меню Data:

    Предварительно таблицу нужно выделить.

    8. Установление связей между таблицами.

    В соответствии с условием задачи, таблицы связаны между собою по полю Num_book.

    Чтобы создать связь между таблицами, сначала нужно (рисунок 16):

    • выделить объект Database Diagram;
    • выбрать команду Add New Diagram из контекстного меню (или из меню Data).

    SQL Server диаграмма добавить

    Рис. 16. Вызов команды добавления новой диаграммы

    В результате откроется окно добавления новой диаграммы Add Table (рисунок 17). В этом окне нужно выбрать последовательно две таблицы Session и Student и нажать кнопку Add.

    таблица диаграмма добавление окно

    Рис. 17. Окно добавления таблиц к диаграмме

    таблица диаграмма добавление рисунок

    Рис. 18. Таблицы Student и Session после добавления их к диаграмме

    Чтобы начать устанавливать отношение между таблицами, надо сделать клик на поле Num_book таблицы Student, а потом (не отпуская кнопку мышки) перетянуть его на поле Num_book таблицы Session.

    В результате последовательно откроются два окна: Tables and Columns (рис. 19) и Foreign Key Relationship (рис. 20), в которых нужно оставить все как есть и подтвердить свой выбор на OK.

    В окне Tables and Columns задается название отношения ( FK_Session_Student ) и названия родительской (Student) и дочерней таблиц.

    связь база данных SQL Server

    Рис. 19. Окно Tables and Columns

    SQL Server свойство отношение

    Рис. 20. Окно настройки свойств отношения

    После выполненных действий будет установлено отношение между таблицами (рисунок 21).

    SQL Server таблица отношение рисунок

    Рис. 21. Отношение между таблицами Student и Session

    Сохранение диаграммы осуществляется точно также как и сохранение таблицы. Имя диаграммы нужно выбрать на свое усмотрение (например Diagram1).

    После задания имени диаграммы откроется окно Save, в котором нужно подтвердить свой выбор (рисунок 22).

    SQL Server изменение таблица

    Рис. 22. Подтверждение сохранения изменений в таблицах

    9. Ввод данных в таблицы.

    Система Microsoft Visual Studio разрешает непосредственно вносить данные в таблицы базы данных.

    В нашем случае, при установлении связи (рис. 19) первичной ( Primary Key Table ) избрана таблица Student. Поэтому, сначала нужно вносить данные в ячейки именно этой таблицы. Если попробовать сначала внести данные в таблицу Session, то система заблокирует такой ввод с выводом соответствующего сообщения.

    Чтобы вызвать режим ввода данных в таблицу Student, нужно вызвать команду Show Table Data из контекстного меню (клик правой кнопкой мышки) или с меню Data (рис. 23).

    SQL Server данные таблица

    Рис. 23. Команда Show Table Data

    Откроется окно, в котором нужно ввести входные данные (рис. 24).

    SQL Server ввод данные таблица

    Рис. 24. Ввод данных в таблице Student

    После внесения данных в таблицу Student нужно внести данные в таблицу Session.

    При внесении данных в поле Num_book таблицы Session нужно вводить точно такие же значения, которые введены в поле Num_book таблицы Student (поскольку эти поля связаны между собой).

    Например, если в поле Num_book таблицы Student введены значения “101”, “102”, “103” (см. рис. 24), то следует вводить именно эти значения в поле Num_book таблицы Session. Если попробовать ввести другое значение, система выдаст приблизительно следующее окно (рис. 25).

    SQL Server ошибка данные таблица

    Рис. 25. Сообщение об ошибке ввода данных связанных таблиц Student и Session

    Таблица Session с введенными данными изображена на рисунке 26.

    таблица данные ввод SQL Server

    Рис. 26. Таблица Session с введенными данными

    Итак, база данных создана. Ввод и обработку данных в таблицах можно реализовать программным путем.

    Читать:
    Почему в excel не печатается вся таблица

Похожие статьи