Как установить entity framework в visual studio 2019
Перейти к содержимому

Как установить entity framework в visual studio 2019

  • автор:

Name already in use

EntityFramework.Docs / entity-framework / core / get-started / overview / first-app.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

Getting Started with EF Core

In this tutorial, you create a .NET Core console app that performs data access against a SQLite database using Entity Framework Core.

You can follow the tutorial by using Visual Studio on Windows, or by using the .NET Core CLI on Windows, macOS, or Linux.

Install the following software:

    with this workload:

    • .NET Core cross-platform development (under Other Toolsets)

    Create a new project

    • Open Visual Studio
    • Click Create a new project
    • Select Console App (.NET Core) with the C# tag and click Next
    • Enter EFGetStarted for the name and click Create

    Install Entity Framework Core

    To install EF Core, you install the package for the EF Core database provider(s) you want to target. This tutorial uses SQLite because it runs on all platforms that .NET Core supports. For a list of available providers, see Database Providers.

    Tools > NuGet Package Manager > Package Manager Console

    Run the following commands:

    Tip: You can also install packages by right-clicking on the project and selecting Manage NuGet Packages

    Create the model

    Define a context class and entity classes that make up the model.

    • In the project directory, create Model.cs with the following code
    • Right-click on the project and select Add > Class
    • Enter Model.cs as the name and click Add
    • Replace the contents of the file with the following code

    EF Core can also reverse engineer a model from an existing database.

    Tip: This application intentionally keeps things simple for clarity. Connection strings should not be stored in the code for production applications. You may also want to split each C# class into its own file.

    Create the database

    The following steps use migrations to create a database.

    Run the following commands:

    This installs dotnet ef and the design package which is required to run the command on a project. The migrations command scaffolds a migration to create the initial set of tables for the model. The database update command creates the database and applies the new migration to it.

    Run the following commands in Package Manager Console (PMC)

    This installs the PMC tools for EF Core. The Add-Migration command scaffolds a migration to create the initial set of tables for the model. The Update-Database command creates the database and applies the new migration to it.

    Как установить entity framework в visual studio 2019

    Данное руководство устарело. Актуальное руководство: Руководство по Entity Framework Core 7

    Платформу Entity Framework Core можно применять в различных технологиях стека .NET. В данном случае мы будем рассматривать базовые моменты платформы на примере консольных приложений, как наиболее простых и не содержащих никакого лишнего кода. Но в последствии также затронем применение EF Core и в других технологиях на конкретных примерах.

    Итак, создадим первое приложение с использованием Entity Framework Core. Для этого создадим в Visual Studio 2019 новый проект по типу Console App (.NET Core) , который назовем HelloApp:

    Первое приложение на Entity Framework Core Создание первого приложения на Entity Framework Core 5

    Итак, Visual Studio создает проект с базовой примитивной структурой, где можно выделить собственно файл логики приложения — файл Program.cs . И чтобы начать работать с EntityFramework Core, нам необходимо вначале добавить в проект пакет EntityFramework Core. Для этого перейдем в проекте к пакетному менеджеру NuGet.

    Однако здесь мы ищем не общий пакет для Entity Framework Core, а пакет для конкретной СУБД. Так, в данном случае мы будем использовать MS SQL Server в качестве СУБД, поэтому нам надо искать пакет Microsoft.EntityFrameworkCore.SqlServer :

    Microsoft.EntityFrameworkCore.SqlServer и начало работы с EntityFramework Core 5

    В качестве альтернативы для добавления пакетов можно использовать Package Manager Console . Для этого в меню Visual Studio перейдем к пункту Tools -> NuGet Package Manager -> Package Manager Console

    В открывшемся внизу в Visual Studio окне Package Manager Console введем команду:

    После выполнения этой команды выполним вторую команду:

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

    Далее нам надо определить модель, которая будет описывать данные. Пусть наше приложение будет посвящено работе с пользователями. Поэтому добавим в проект новый класс User:

    Это обычный класс, который содержит несколько свойств. Каждое свойство будет сопоставляться с отдельным столбцом в таблице из бд.

    Надо отметить, что Entity Framework требует определения ключа элемента для создания первичного ключа в таблице в бд. По умолчанию при генерации бд EF в качестве первичных ключей будет рассматривать свойства с именами Id или [Имя_класса]Id (то есть UserId).

    Взаимодействие с базой данных в Entity Framework Core происходит посредством специального класса — контекста данных. Поэтому добавим в наш проект новый класс, который назовем ApplicationContext и который будет иметь следующий код:

    Основу функциональности Entity Framework Core для работы с MS SQL Server составляют классы, которые располагаются в пространстве имен Microsoft.EntityFrameworkCore . Среди всего набора классов этого пространства имен следует выделить следующие:

    DbContext : определяет контекст данных, используемый для взаимодействия с базой данных

    DbSet/DbSet<TEntity> : представляет набор объектов, которые хранятся в базе данных

    DbContextOptionsBuilder : устанавливает параметры подключения

    В любом приложении, работающим с БД через Entity Framework, нам нужен будет контекст (класс производный от DbContext). В данном случае таким контекстом является класс ApplicationContext.

    И также в классе определено одно свойство Users, которое будет хранить набор объектов User. В классе контекста данных набор объектов представляет класс DbSet<T> . Через это свойство будет осуществляться связь с таблицей объектов User в бд.

    Кроме того, для настройки подключения нам надо переопределить метод OnConfiguring . Передаваемый в него параметр класса DbContextOptionsBuilder с помощью метода UseSqlServer позволяет настроить строку подключения для соединения с MS SQL Server. В данном случае мы определяем, что в качестве сервера будет использоваться движок localdb, который предназначен специально для разработки, ( «Server=(localdb)\\mssqllocaldb» ), а файл базы данных будет называться helloappdb ( «Database=helloappdb» ).

    И также стоит отметить, что по умолчанию у нас нет базы данных. Поэтому в конструкторе класса контекста определен вызов метода Database.EnsureCreated() , который при создании контекста автоматически проверит наличие базы данных и, если она отсуствует, создаст ее.

    Теперь определим сам код программы, который будет взаимодействовать с созданной БД. Для этого изменим класс Program следующим образом:

    Так как класс ApplicationContext через базовый класс DbContext реализует интерфейс IDisposable , то для работы с ApplicationContext с автоматическим закрытием данного объекта мы можем использовать конструкцию using .

    В конструкции using создаются два объекта User и добавляются в базу данных. Для их сохранения нам достаточно использовать метод Add : db.Users.Add(user1)

    Чтобы получить список данных из бд, достаточно воспользоваться свойством Users контекста данных: db.Users

    В результате после запуска программа выведет на консоль:

    И после добавления мы можем найти базу данных в окне SQL Server Object Explorer (открыть данное окно можно через меню View->SQL Server Object Explorer ). Там мы можем раскрыть и посмотреть содержимое ее таблиц:

    Создание базы данных в EF Core

    Таким образом, Entity Framework Core обеспечивает простое и удобное управление объектами из базы данных. При том в данном случае нам не надо даже создавать базу данных и определять в ней таблицы. Entity Framework все сделает за нас на основе определения класса контекста данных и классов моделей. И если база данных уже имеется, то EF не будет повторно создавать ее.

    How to Build a CRUD Application with ASP.NET Core 3.0 & Entity Framework 3.0 using Visual Studio 2019

    In this blog, I am going to provide a walk-through on developing a web application using ASP.NET Core 3.0, connecting it to a database (database-first) using the Entity Framework Core 3.0 command, and performing CRUD operations using scaffolding (code generator). I am going to develop a sample application for inventory management with basic operations.

    ASP.NET Core is a web framework from Microsoft. It is an open-source, cross-platform, cloud-optimized web framework that runs on Windows using .NET Framework and .NET Core, and on other platforms using .NET Core. It is a complete rewrite that unites ASP.NET MVC and Web API into a single programming model and removes system-related dependencies. This helps in deploying applications to non-Windows servers and improves performance.

    Note: In this demo application, I have used ASP.NET Core 3.0 Preview 8, Entity Framework Core 3.0 Preview 8, with Visual Studio 2019 16.3.0 Preview 2.0.

    Prerequisites

    A .NET Core application can be developed using these IDEs:

    • Visual Studio
    • Visual Studio Code
    • Command Prompt

    Here, I am using Visual Studio to build the application. Be sure that the necessary software is installed:

    • Visual Studio 2019 16.3.0 Preview 2.0
    • NET Core 3.0 Preview 8
    • SQL Server 2017

    Create database

    Let’s create a database on your local SQL Server. I hope you have installed SQL Server 2017 in your machine (you can use SQL Server 2008, 2012, or 2016, as well).

    Step 1: Open Visual Studio 2019.

    Step 2: Open SQL Server Object Explorer and click Add SQL Server.

    Step 3: Here we have an option to choose from the local machine’s SQL Server, connected via network, and the Azure SQL database. I have chosen the local SQL Server instance. I provide the SQL Server details and click Connect. The SQL Server will be listed in Explorer.

    Step 4: Right-click on a database node and create a new database ( Inventory).

    Step 5: Now we have the database in place. Click on our database and choose New Query.

    Step 6: For this application, I am going to create a table called Products with basic attributes. Paste the following SQL query into the Query window to create a Products table.

    Step 7: Click the Run icon to create the table. Now we have the table needed for our application.

    Create an ASP.NET Core application

    Follow these steps to create an ASP.NET Core application.

    Step 1: In Visual Studio 2019, click on File -> New -> Project.

    Step 2: Choose the Create a new project option.

    Step 3: Select the ASP.NET Core Web Application template.

    Step 4: Enter project name and click Create.

    Step 5: Select .NET Core and ASP.NET Core 3.0 and choose the Web Application (Model-View-Controller) template.

    Uncheck the Configure for HTTPS under the Advanced options (in a development environment, we have no need of SSL).

    Click Create. Then the sample ASP.NET Core application will be created with this project structure.

    Install NuGet packages

    The following NuGet packages should be added to work with the SQL Server database and scaffolding. Run these commands in Package Manager Console:

    • Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 3.0.0-preview8–19413–06 This package helps generate controllers and views.
    • Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0-preview8.19405.11 This package helps create database context and a model class from the database.
    • Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0-preview8.19405.11 The database provider allows Entity Framework Core to work with SQL Server.

    Scaffolding

    ASP.NET Core has a feature called scaffolding, which uses T4 templates to generate code of common functionalities to help keep developers from writing repeat code. We use scaffolding to perform the following operations:

    • Generate entity POCO classes and a context class for the database.
    • Generate code for create, read, update, and delete (CRUD) operations of the database model using Entity Framework Core, which includes controllers and views.

    Connect application with database

    Run the following scaffold command in Package Manager Console to reverse engineer the database to create database context and entity POCO classes from tables. The scaffold command will create POCO class only for the tables that have a primary key.

    Scaffold-DbContext “Server=ABCSERVER;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

    • Connection-Sets connection string of the database.
    • Provider-Sets which provider to use to connect database.
    • OutputDir-Sets the directory where the POCO classes are to be generated.

    In our case, the Products class and Inventory context class will be created.

    Open the Inventory Context class file. You will see the database credentials are hard coded in the OnConfiguring method.

    It’s not good practice to have SQL Server credentials in C# class, considering the security issues. So, remove this OnConfiguring method from context file.

    And move the connection string to the appsettings.json file.

    Then we can register the database context service ( InventotyContext) during application startup. In the following code, the connection string is read from the appsettings file and passed to the context service.

    Then this context service is injected with the required controllers via dependency injection.

    Perform CRUD operations

    Now we set up the database and configure it to work with Entity Framework Core. We’ll see how to perform CRUD operations.

    Right-click on the controller folder, select add new item, and then select controller. Then this dialog will be displayed.

    Select the MVC Controller with views, using Entity Framework option and click Add.

    We need to choose a database model class and data context class, which were created earlier, and click Add.

    That’s it, we’re done. The scaffolding engine uses T4 templates to generate code for controller actions and views in their respective folders. This is the basic version of code; we can modify it as needed.

    Please find the files created,

    Now we have fully functional CRUD operations on the Products table.

    Then, change the default application route to load the Products Controller instead of the home controller. Open the Startup.cs file and under the Configure method, change the default controller to Products.

    With the help of the scaffolding engine, developers need not write CRUD operations for each database model.

    Run application

    Click Run to view the application. A new browser tab will open and we’ll be able to see the product listing page. Since there is no product in the inventory, it’s empty.

    Click Create New to add new products to the inventory.

    After entering the details, click Create. Now we should see newly created products in the listing page as in the following screenshot. I have added three more products.

    Click Details to view the product details.

    Click Edit to update product details.

    Click Delete to delete a product. Confirmation will be requested before it’s deleted from the database.

    Without writing a single line of code, we are able to create an application with basic CRUD operations with the help of the scaffolding engine.

    I have shared the sample application in this GitHub location. Extract the application, change the connection string in the appsettings.json file that points to your SQL Server, and run the application.

    Conclusion

    In this blog, we have learned how to create an ASP.NET Core application and connect it to a database to perform basic CRUD operations using Entity Framework Core 3.0 and a code generation tool. I hope it was useful. Please share your feedback in the comments section below.

    The Syncfusion ASP.NET Core UI controls library is the only suite that you will ever need to build an application since it contains over 65 high-performance, lightweight, modular, and responsive UI controls in a single package. Download our free trial from here. You can also explore our online demos here.

    If you have any questions or require clarifications about these controls, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

    How to get EF Core — NuGet Package

    EF Core is available as a Nuget Package that can be added to your project in many ways depending on the project type and the tools available to you.

    Visual Studio Package Manager

    Users of Visual Studio can install Entity Framework Core via one of the package management tool options regardless of the project type (.NET Core or the full .NET Framework): the NuGet Package Manager UI; or the Package Manager Console.

    Nuget Package Manager UI

    Go to Tools » NuGet Package Manager » Manage NuGet Packages For Solution
    NuGet Package Manager UI

    Ensure that Browse is selected and type "entityframeworkcore" into the search box
    Browse packages

    Click on the provider that you want to install. SQL Server is selected in this case.
    Select package

    Check the project that you want to install the package into, then click Install
    Install Package

    Review the changes that are about to be made to your project (unless you have previously ticked the box to prevent this dialog from appearing)
    Review Changes

    Finally, accept the terms of the various licenses associated with the packages that are about to be installed
    Accept Licenses

    Package Manager Console

    Go to Tools » NuGet Package Manager » Package Manager Console
    Package Manager Console

    Ensure that the correct project is selected in the "Default Project" dropdown, and type install-package microsoft.entityframeworkcore.sqlserver to install the SQL Server provider.
    Install Package

    Hit return, and the installation process should start.

    Command Line Tools

    You can use the .NET Core command line tools to install Entity Framework Core. Once you have created your project, navigate to the folder containing the .csproj (or project.json) file and execute the following command:

    You also need the Entity Framework Core tools if you want to make use of EF commands for migrations, scaffolding, etc, so type the following command:

    Project.json

    The project.json file has been deprecated in favor of a .csproj file, but for older .NET Core projects on any platform, you can modify the project.json file to install Entity Framework Core. The following example shows a basic project.json file amended to include the 1.1.0 version of the SQL Server provider:

    A reference to the tooling is also included in both the dependencies section and the tools section. These are required if you want to run commands for scaffolding or migrations.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *