dir.by  
  Поиск  
Компьютер, программы
WPF. Windows Presentation Foundation (standalone .exe file)
 Entity Framework в приложении WPF (Code First) 
посмотрели 19077 раз
обновлено: 21 June 2018
Entity Framework предоставляет возможность работы с Базой данных через C# код.
Рассмотрим подход Code First (пишем C# код, а таблицы в Базе данных создаются автоматически по C# коду).
План (7 шагов)
Шаг 1. Создаем новый WPF проект
Шаг 2. Добавляем библиотеку Entity Framework используя NuGet
Нажимаем в меню: ToolsNuGet Package ManagerManage NuGet Packages for Solution...
Нажимаем кнопку "Install"
Let's look at что подключилось >> ...
Шаг 3. Установка Microsoft SQL Server (для хранения базы данных)
Мы будем использовать Microsoft SQL Server для хранения базы данных.
Если у Вас не установлена нужно установить Microsoft SQL Server 2012... (или другую версию)
Шаг 4. Создаем соединиение с Базой данных Microsoft SQL Server в файле App.config
Добавляем соединение <connectionStrings>...</connectionStrings> к Базе данных в файле App.config
Новые добавленные строчки помеченные синим
  Файл: App.config
<?xml version="1.0" encoding="utf-8"?>
<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>

     <startup>
          <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
     </startup>
    
     <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.SqlConnectionFactory, EntityFramework" />
          <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 (на картинке нарисовано).
Шаг 5. Добавим класс Book и класс UserContext для работы с Базой данных
Для подключения к базе данных через Entity Framework, нам нужен посредник - контекст данных.
Контекст данных представляет собой класс, производный от класса DbContext.
Контекст данных содержит одно или несколько свойств типа DbSet, где T представляет тип объекта, хранящегося в базе данных

Класс UserContext это наш контекст данных
Наш контекст данныхсоздаст базу данных MyDatabase1 (если ее не существует)
Класс Book создаст таблицу Books и заполнит данными.

Новые добавленные строчки помеченные синим
  C#  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Data.Entity;

namespace WpfApplication10
{
     public class Book
     {
          public int Id { get; set; }
          public string Name { get; set; }
          public int Price { get; set; }
     }

     class UserContext : DbContext
     {
          public UserContext() : base("MyConnection1")
          { }

          public DbSet<Book> Books { get; set; }
     }


     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
          public MainWindow()
          {
               InitializeComponent();

               // 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();
               }

          }
     }
}
Шаг 6. Запускаем WPF приложение
Нажимаем вверху на зеленый треугольник
Приложение запустилось
 
После запуска приложения, выполнится 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
Example "Set the width of the element as a percentage of the width of the parent element" (width in percentage), write your IValueConverter | C# WPF application
 
Next topic →
Example "Create your own WPF element using Style and a new xaml file. The new element is: at the top Title, at the bottom the text in the frame. Using Binding | C# WPF application
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
WPF Simple New Application
Creating a New WPF Application | C#
WPF layout
Making a layout with DockPanel and StackPanel in WPF
Events
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
Example "Get the mouse coordinates when you left-click on Grid and draw a line"| C# WPF application
Example "When you double-click on Grid, we show the message"| C# WPF application
WPF elements
Label
Example "Setting the text in Label" via c# code | WPF application
FontAwesome icons
Example "I show icons, for the icon I connect the fontawesome5" library | C# WPF application
Example "I make animations for icons, library fontawesome5" | C# WPF application
 <BR>
TextBlock
Example "Set the text in the TextBlock using Binding". Let"s also add double Bindning using INotifyPropertyChanged | C# WPF application
Example "Several TextBlocks (showing the texts) and making the element where mouse (mouse over)" | C# WPF application
Example "Get the mouse coordinates when you left-click on TextBlock"| Screen Coordinates and Relative Coordinates | C# WPF application
Button
Example "Get the mouse coordinates when you click the left mouse button on Button"| Screen Coordinates and Relative Coordinates | C# WPF application
TextBox
Example "Installing and getting text in a TextBox using Binding" | C# WPF application
Example "Set text in TextBox" via c# code | WPF application
 <BR>
TextBox with Place Holder
Example "Showing the Place Holder in TextBox" | WPF application
Example "Showing a Place Holder with an icon in TextBox", for the icon I include the fontawesome5 library | WPF application
 <BR>
TextBox with text validation
Example "Set the text in the TextBox using Binding and do validation (if the text is not correct)" | C# WPF application
 <BR>
ComboBox
Example "In ComboBox, we do text editing. Getting the text using Binding" | C# WPF application
 <BR>
ItemsControl
Example "ItemsControl, button and click handler" | WPF application
Grid
What is Grid in WPF
How to Add RowDefinition, ColumnDefinition to a Grid (with the mouse in the XAML design editor) | C# WPF application
Adding vertical scrolling | WPF application
DataGrid
Example "DataGrid doing bind data", button and click handler in DataGrid, text alignment in DataGrid, scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
How do I color row when I click on row (change background for selected row) in DataGrid? | C# WPF application
How do I highlight a row DataGrid (make background) ? | C# WPF application
Example "DataGrid: sorting the column according to our own algorithm (Custom Sort)" | WPF application
DataGrid inside DataGrid
Example of an employee portfolio with task descriptions: "DataGrid inside DataGrid using RowDetailsTemplate" | WPF application
 <BR>
ListView
Example "In the ListView, expand the column when adding data (auto column width)" | WPF application
Example "In the ListView, we use ItemTemplate DataTemplate" | WPF application
 <BR>
ScrollViewer
Adding vertical scrolling | WPF application
How do I scroll for DataGrid? | C# WPF application
Scrolling for DataGrid (so that scrolling works when we spin the mouse wheel and the mouse is outside the scroll bar) | C# WPF application
Example "Do ScrollBar less(more) in ScrollViewer" | C# WPF application
Resource file
Add an image (jpg, bmp, png) to the project and mark it as Resource | C# WPF application
Image
In the Image element, show the image (jpg, bmp, png) from Resource | C# WPF application
Select the image (jpg, bmp, png) from the computer and show it in the Image element. Saving the image to the database | C# WPF application
Example "In the Image element, make a Binding for Source" | C# WPF application
Example "Convert the base64 text to a Bitmap image and show it in the Image element" | C# WPF application
Example "Open an SVG file and show the image in the Image element" | C# WPF application
 <BR>
Canvas
Example "Create a Canvas and draw a picture" C# WPF
Example "Drawing a picture with movement on Canvas" C# WPF
Example "Drawing a picture with motion and sprite animation on Canvas" C# WPF
 <BR>
Line
How to Draw a Line | C# WPF application
Example "Create and draw a line by left-clicking on Grid"| Grid Line | C# WPF application
Convert the image to XAML Path Geometry
Convert SVG to XAML (using Adobe Illustrator), populate the Path Data Geometry, show the lines on the screen | C# WPF application
Convert SVG to XAML (using Dias SVG to UWP XAML Converter), populate the Path Data Geometry, show the lines on the screen | C# WPF application
How to Convert PNG to SVG to XAML | C# WPF application
Converter SVG to XAML | WPF C#
How to Convert XAML to SVG | C# WPF application
ViewBox
Example "ViewBox Binding for Left, Top, Width, Height, ContetnPresenter binding" | C# WPF application
Width by percentage
Divide the screen vertically (by width) into 2 equal parts of the screen (width1 = 50%, width2 = 50%), use Grid | C# WPF application
Split the screen vertically (by width) into 2 parts (width1 = 70%, width2 = 30%), using Grid | C# WPF application
Example "Set the width of the element as a percentage of the width of the parent element" (width in percentage), write your IValueConverter | C# WPF application
Database (Entity Framework)
Entity Framework in a WPF application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Creating Your WPF Elements
Example "Create your own WPF element using Style and a new xaml file. The new element is: at the top Title, at the bottom the text in the frame. Using Binding | C# WPF application
Example "Create your new WPF element with your own properties in the new cs and xaml files. In WPF, a new element: Title at the top, text at the bottom, and in the box | C# WPF application
WPF application with Prism library (MVVM design pattern)
Create a new WPF application with Prism Unity (splitting the project into Services, Views, ViewModels folders). MVVM (Model-View-ViewModel) Patern | C#
WPF application with Prism Unity. In the Tab app and splitting into separate xamls using Region.
WPF application with Locator (MVVM design pattern)
Creating a new WPF application with Locator (dividing the project into Views, ViewModels folders)
How do I add Dependency Injection, boot from appsettings.json in a new WPF application?
Automated Tests
Writing an automated test for a WPF C# application (using Nuget.Appium and the AutomationProperties.AutomationId property)
Interview Questions
What is the difference between static resource and dynamic resource? | WPF C#
Additional topics, questions
Open the properties window for a graphic element in WPF application C#
Errors
Error "To run this application, you must install .NET. Would you like to download it now?" | I run WPF the application on C#
Books
WPF Study Books

  Ваши вопросы присылайте по почте: info@dir.by