Закрыть
×
=0) { let js = text.slice(pos1, pos2); + '<\/' + "script" + '>'; arrText.push(js); // next pos1 = pos2; continue; } } } break; } return arrText; } function OpenDialog(parentDiv, urlContent) { parentDiv = document.getElementById('modal-background'); // new !!!!!!! parentDiv.appendChild(document.getElementById('modal-template')); document.getElementById('modal-background').style.display = "flex"; // !!!!! block document.getElementById('modal-template').style.display = "flex"; // !!!!! document.getElementById('modal-body').innerHTML = ""; post_url(urlContent, "", function(text_from_server) { var element = document.getElementById('modal-body'); element.innerHTML = text_from_server; // add scripts var arrJSText = get_scripts(text_from_server); for (var i=0; i
dir.by
Праздники ...
Праздники ...
День города Минска (2-ая суббота сентября) (9 и 10 сентября 2023)
Концерты, выставки ...
Концерты, выставки ...
Полина Гагарина|||г. Минск 10 октября 2026
Афишу
Спорт занятия ...
Спорт занятия ...
Бильярд
Спорт занятие
Компьютер, программы...
Компьютер, программы...
Объявления ...
Объявления ...
ПОЛЗУНЫ рост 68, 74
Объявление
Новости ...
Новости ...
Форум ...
Форум ...
обсуждение...
Поиск
Концерты
Спорт
Форум
Компьютер
Компьютер, программы
→
ASP.NET MVC (Model-View-Controller website)
Entity Framework в приложении ASP.NET MVC (Code First)
посмотрели
10199
раз
обновлено: 13 January 2019
Entity Framework
предоставляет возможность работы с
Базой данных
через
C#
код.
Рассмотрим подход
Code First
(пишем
C#
код, а таблицы в
Базе данных
создаются автоматически по
C#
коду).
План (7 шагов)
Шаг 1.
Создаем новый ASP.NET MVC проект
Шаг 2.
Добавляем библиотеку Entity Framework используя NuGet
Шаг 3.
Установка Microsoft SQL Server (для хранения базы данных)
Шаг 4.
Создаем соединиение с Базой данных Microsoft SQL Server в файле Web.config
Шаг 5.
Добавим класс Book и класс UserContext для работы с Базой данных
Шаг 6.
Запускаем ASP.NET MVC приложение
Шаг 7.
Проверяем как создалась наша База данных и таблица в Microsoft SQL Server
Шаг 1. Создаем новый ASP.NET MVC проект
Создаем
новое приложение ASP.NET MVC ...
Шаг 2. Добавляем библиотеку Entity Framework используя NuGet
Нажимаем в меню:
Tools
→
NuGet Package Manager
→
Manage NuGet Packages for Solution...
Нажимаем кнопку "Install"
Нажимаем кнопку "OK"
Hide что подключилось << ...
Let's look at что подключилось >> ...
В проект в
папку References
добавились packages:
•
EntityFramework
•
EntityFramework.SqlServer
В файл Web.config добавились новые строчки
выделенныы
зеленым цветом
Файл:
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http:
//go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http:
//go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Шаг 3. Установка Microsoft SQL Server (для хранения базы данных)
Мы будем использовать
Microsoft SQL Server
для хранения базы данных.
Если у Вас не установлена нужно
установить Microsoft SQL Server 2012...
(или другую версию)
Шаг 4. Создаем соединиение с Базой данных Microsoft SQL Server в файле Web.config
Добавляем соединение
<connectionStrings>...</connectionStrings>
к Базе данных в файле
Web.config
Новые добавленные строчки помеченные
синим
Файл:
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http:
//go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http:
//go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<connectionStrings>
<add name="MyConnection1" connectionString="Data Source=EVGENI\MSSQLSERVER2012;Initial Catalog=MyDatabase1;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
На заметку!
•
Initial Catalog=
MyDatabase1
это название базы данных. Если такое название не существует то новая база данных будет создана.
•
name="
MyConnection1
"
пишем любой текст это имя соединения. Это имя соединения будем использовать в C# классах.
•
Data Source=
EVGENIMSSQLSERVER2012
это имя сервера базы данных (SQL Server name). Сервер базы данных может находится локально или на другом компьютере. Имя сервера базы данных появляется при открытии
SQL Server Management Studio
(на картинке нарисовано).
Читать подробнее
создание <connectionStrings> в .config файле...
Шаг 5. Добавим класс Book и класс UserContext для работы с Базой данных
Нажмем правой клавишей мыши на папку
"Models"
→
Add
→
New Item
Для подключения к
базе данных
через
Entity Framework
, нам нужен посредник -
контекст данных
.
Контекст данных
представляет собой класс, производный от класса
DbContext
.
Контекст данных
содержит одно или несколько свойств типа
DbSet
, где
T
представляет тип объекта, хранящегося в
базе данных
Класс
UserContext
это наш
контекст данных
Наш
контекст данных
создаст базу данных
MyDatabase1
(если ее не существует)
Класс
Book
создаст таблицу
Books
и заполнит данными.
Новые добавленные строчки помеченные
синим
C#
Файл:
UserContext.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using System.Data.Entity;
namespace
WebApplication2.Models
{
public
class
Book
{
public
int
Id { get; set; }
public
string
Name { get; set; }
public
int
Price { get; set; }
}
public
class
UserContext
: DbContext
{
public
UserContext() : base(
"MyConnection1"
)
{
}
public
DbSet<Book> Books { get; set; }
}
}
В файле Controllers\
HomeController.cs
напишем код создание и заполнение базы данных.
C#
Файл:
HomeController.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
using WebApplication2.Models;
namespace
WebApplication2.Controllers
{
public
class
HomeController
: Controller
{
// GET: Home
public
ActionResult Index()
{
// add data
using(UserContext db =
new
UserContext())
{
// создаем объекты Book
Book book1 =
new
Book { Name =
"Граф Монтекристо"
, Price = 123 };
Book book2 =
new
Book { Name =
"Властелин колец"
, Price = 267 };
Book book3 =
new
Book { Name =
"Три кота"
, Price = 125 };
// добавляем объекты Book в контекст данных
db.Books.Add(book1);
db.Books.Add(book2);
db.Books.Add(book3);
// сохраняем контекст данных в базу данных
db.SaveChanges();
}
return
View();
}
}
}
Шаг 6. Запускаем ASP.NET MVC приложение
Нажимаем вверху на зеленый треугольник
Приложение запустилось
После запуска приложения, выполнится
C#
код который:
• создаст Базу данных
"MyDatabase1"
(если такой нет)
• создаст таблицу
Books
(если такой нет)
• добавит значения в таблицу
Books
Name="Граф Монтекристо" Price=123
Name="Властелин колец" Price=267
Name="Три кота" Price=125
Шаг 7. Проверяем как создалась наша База данных и таблица в Microsoft SQL Server
Note!
You must have
Microsoft SQL Server
installed. If you don't have it, then
need to download and install
Microsoft SQL Server
...
Note!
You must have
SQL Server Management Studio
installed. If you don't have it, then
need to download and install
SQL Server Management Studio
...
To open
SQL Server Management Studio
, we click on the icon on the desktop:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
A window will appear and press the
"Connect"
button:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
After 20 seconds, we will see that
SQL Server Management Studio
is loaded:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
Смотрим значения в таблице в SQL Server Management Studio
Шаг 1.
Открываем SQL Server Management Studio
Note!
You must have
Microsoft SQL Server
installed. If you don't have it, then
need to download and install
Microsoft SQL Server
...
Note!
You must have
SQL Server Management Studio
installed. If you don't have it, then
need to download and install
SQL Server Management Studio
...
To open
SQL Server Management Studio
, we click on the icon on the desktop:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
A window will appear and press the
"Connect"
button:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
After 20 seconds, we will see that
SQL Server Management Studio
is loaded:
Old version
SQL Server Management Studio
(this is version 18)
New version
SQL Server Management Studio
(this is version 22)
Шаг 2.
Смотрим значения в таблице
Раскрываем базу данных
MyDatabase1
Нажимаем правой клавишей мыши на таблице
dbo.Books
и нажимаем
Select Top 1000 Rows
Смотрим на значения:
Видим, что автоматически:
• создалась новая база данных
MyDatabase1
(если такой не было)
• создалась новая таблица
Books
(если такой не было)
• в таблице
Books
добавились значения
Таблица
Books
Id
Name
Price
1
Граф Монтекристо
123
2
Властелин колец
267
3
Три кота
125
На заметку!
Если запустим программу второй раз, то увидим что в таблице
Books
уже
6 строчек
.
Если запустим программу третий раз, то увидим что в таблице
Books
9 строчек
.
Если запустим программу четвертый раз, то увидим что в таблице
Books
12 строчек
.
То есть если таблица
Books
существет, то
при каждом запуске программы
добавляются
3 строчки
.
← Previous topic
Ajax object (this is the AjaxExtensions class) in MVC ASP.NET
Next topic →
What is authentication (login/register/logout) in the MVC ASP.NET?
Your feedback ... Comments ...
Your Name
Your comment
(www links can only be added by a logged-in user)
+ Picture
•
What is MVC in ASP.NET ?
•
Creating a new application ASP.NET MVC
Controller
•
Pass the data from the controller to the view in the MVC ASP.NET. Using ViewBag, ViewData, TempData, Model (strongly typed view)
View
•
What are Razor View and Operators in MVC ASP.NET
•
Create a variable and display it in View in the MVC ASP.NET
•
@using inside View in the MVC ASP.NET
•
@foreach(var item in arr) {...} inside the View in the MVC ASP.NET
•
@DateTime.Now inside the View in the MVC ASP.NET
•
How to find the name of the controller inside the View in the MVC ASP.NET
•
Display [DateTime | Date only | Time only] in the desired format in the MVC ASP.NET
Views
•
Strongly-typed-view in MVC ASP.NET
...
•
Master View using @RenderBody() in the MVC ASP.NET
•
Master View using @RenderBody() and additional sections @RenderSection in the MVC ASP.NET
...
•
Partial View in the MVC ASP.NET. Embed a partial representation @Html.Partial("My1") and @{ Html.RenderPartial("My1");}
•
When you click submit inside the partial view, the controller method is called ajax. The controller method should return PartialView(model) | ASP.NET MVC
...
•
Strongly-typed partial view in the MVC ASP.NET
Create the ViewModels folder. This is a good programming style for transferring data from the Controller to the View
•
Create the ViewModels folder. Create your class in the ViewModels folder. This is a good programming style for transferring data from the Controller to the View. Web Application ASP.NET MVC
Attributes. Use the attributes in the ViewModels (to show the combo buttons in the view). Using attributes in the Controller (to improve methods)
•
Attribute [Display(Name = "... ")] is described in the C# class and used in @Html.LabelFor, @Html.DisplayNameFor in the MVC ASP.NET
•
The attribute [Required(ErrorMessage = "Please enter a name")] is described for a property in the C# class and requires the property to be populated if the ErrorMessage error in the MVC ASP.NET is not filled in the screen
•
The attribute [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] is described for a property in a C# class and checks that property for correctness on the server via the IsValidAuthor method in conroller Home, if the method returns false, then there will be an ErrorMessage error on the screen in the MVC ASP.NET
•
The [HiddenInput(DisplayValue=false)] attribute is described in the C# class and is used in @Html.HiddenFor in the MVC ASP.NET
Routing
Links and redirects in the view
•
@Html.ActionLink inside the View in the MVC ASP.NET
•
@Html.RouteLink inside the View in the MVC ASP.NET
•
@Url.Action inside the View in the MVC ASP.NET
•
@Url.RouteUrl inside the View in the MVC ASP.NET
•
@Url.Content inside the View in the MVC ASP.NET
Bootstrap in MVC
•
Add and include Bootstrap (css, js files) to ASP.NET MVC project
JQuery in MVC
•
Connecting JQuery to ASP.NET MVC project
•
Using JQuery, we get the contents of the View in the MVC ASP.NET. Example: $.get("/Home/Index", function (data) {...}) ...
MVC AjaxExtensions class (asynchronous data retrieval)
•
Plugging jQuery & AJAX into ASP.NET MVC project
•
Using Ajax.ActionLink, get the contents of the View and insert it into the div in the MVC ASP.NET
•
Ajax object (this is the AjaxExtensions class) in MVC ASP.NET
Database (Entity Framework) in MVC ASP.NET
•
Entity Framework in the ASP.NET MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Authentication (login/register/logout)
•
What is authentication (login/register/logout) in the MVC ASP.NET?
•
Example: Authentication (login/register/logout) in MVC ASP.NET using FormsAuthentication.SetAuthCookie(model. Name, true);
Authorization (admin/user/...)
•
What is authorization (admin/user/...) in the MVC ASP.NET?
•
Example: Authorization (admin/user/...) in MVC ASP.NET using the RoleProvider role provider
Writing the appendix "Planning tasks" in the MVC ASP.NET
•
Creating an empty application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
•
Adding Bootstrap & jQuery libraries to the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
•
Create a master view (main menu & button login using Bootstrap) in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
•
Add the "Home" controller and the "Index" view (the main page in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
•
Add the Entity Framework library and create a connection to the Database in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
•
Authentication (login/register/logout) in the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
•
Add the class "Task" to save tasks, tasks to the database in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
•
Adding nUnit in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Additional topics, questions
•
Why is MVC ASP.NET better ASP.NET Web Forms?
•
Choosing between ASP.NET Core and ASP.NET?
•
How to choose an Internet browser to run a .NET project in it
•
How do I find the local address and port of your ASP.NET MVC application?
•
Scriptsindex.d.ts(8,1): error TS1008: Build:Unexpected token; "module, class, interface, enum, import or statement" expected. Scriptsindex.d.ts(8,13): error TS1005: Build:";" expected. in Visual Studio 2017 in the ASP.NET MVC app
•
Error "unable to connect to web server "iis express" | ASP.NET MVC | Visual Studio 2017
•
Error "This site can"t be reached" when run ASP.NET application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW Sites to Learn ASP.NET MVC
•
Sites to learn ASP.NET MVC
Ваши вопросы присылайте по почте:
info@dir.by