0% found this document useful (0 votes)
42 views26 pages

PRN212 Using EntityFramework and WPF Template

PRN212

Uploaded by

khanghnpde170694
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views26 pages

PRN212 Using EntityFramework and WPF Template

PRN212

Uploaded by

khanghnpde170694
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Building an Template Application using WPF

application and Entity Framework Core


In this exercise, you will:

 Use the Visual [Link] to create WPF application and Class Library (.dll) project.
 Create a SQL Server database named MyStoreDB that has a Product table.
 Apply Repository pattern in a project.
 Add CRUD action methods to WPF application.
 Run the project and test the WPF application actions.

1|Page
3. Database Design (MyStore)
Tạo CSDL từ script hoặc hình ảnh đã cho

Script:

-- (tuỳ chọn) Xoá nếu đã tồn tại

IF OBJECT_ID('[Link]','U') IS NOT NULL

DROP TABLE [Link];

GO

CREATE TABLE [Link] (

-- Nếu muốn tự tăng, đổi dòng dưới thành: ProductID INT IDENTITY(1,1) NOT NULL

ProductID INT NOT NULL,

ProductName NVARCHAR(40) NOT NULL,

CategoryID INT NOT NULL,

UnitsInStock SMALLINT NULL,

UnitPrice MONEY NULL,

CONSTRAINT PK_Products PRIMARY KEY (ProductID)

);

GO

INSERT INTO [Link] (ProductID, ProductName, CategoryID, UnitsInStock, UnitPrice)


VALUES

(1 , N'Chai nước suối 500ml', 1, 120, 5.000),

(2 , N'Bánh quy bơ 200g', 1, 80, 25.000),

2|Page
(3 , N'Cà phê hạt Arabica 1kg', 2, 35, 210.000),

(4 , N'Trà xanh túi lọc (25 túi)', 2, 150, 39.000),

(5 , N'Đường tinh luyện 1kg', 3, 200, 22.000),

(6 , N'Sữa tươi 1L', 4, 60, 34.000),

(7 , N'Dầu ăn 1L', 3, 90, 45.000),

(8 , N'Mì gói hộp 30 gói', 1, 40, 115.000),

(9 , N'Nước ngọt lon 330ml', 1, 300, 10.000),

(10, N'Kẹo bạc hà 100g', 1, 75, 18.000),

(11, N'Hạt điều rang muối 250g', 2, 25, 95.000),

(12, N'Ngũ cốc ăn sáng 375g', 4, 50, 62.000);

Table Products

Activity 01: Build a solution by Visual [Link]


Create a Blank Solution named ProductManagementDemo then add new a Class Library
project named BusinessObjects, DataAccessObjects, Repositories, Services and a WPF
project named ProductManagement

3|Page
Step 01. Create a Blank solution.
Step 02. Create 4 Class Library projects.
Step 03. Create a WPF project.

Note:
 Data Source in this case is the SQL Server Database
 Services Project – This project represents a layer or component responsible for
implementing the business logic of an application.
 Repository Project – This project provides an abstraction layer between the
application’s business logic and the underlying data source.
 Data Access Layer Project – This project used to abstract and encapsulate the logic for
accessing data from a data source, such as a database.

4|Page
Activity 02: Write codes for the BusinessObjects project
Step 01. Install the following packages from NuGet:
 [Link] --version 8.0.1
 [Link] --version 8.0.1
 [Link] --version 8.0.0
 [Link]

Check the tool for EFCore (install/uninstall tool if needed) (dotnet SDK 8.0.202)
dotnet tool list --global

dotnet tool uninstall --global dotnet-ef (nếu dotnet-ef không trùng version với các
pakages m đã install)
dotnet tool install --global dotnet-ef --version 8.0.1

Step 02. Right-click on project (Bussiness) , select Open In Terminal. On Developer


PowerShell dialog execute the following commands to generate model:
 Implement ORM
 Chú ý: Build Bussiness trước

5|Page
Mở terminal đúng ngay tại đg dẫn của Bussiness

dotnet ef dbcontext scaffold “Server= LAPTOP-PJCV33QV\SQLEXPRESS;


Database= MyStore; Uid=sa; Pwd=123; TrustServerCertificate=True;”
[Link] --output-dir ./
 Move the [Link] to DataAccessLayer Project

Activity 03: Write codes for the DataAccessLayer project

Step 01. On the DataAccessLayer project, add a class named [Link] and write codes
as follows:

The details of functions in [Link]:


using BussinessLayer;
using [Link];
using System;
using [Link];
using [Link];
using [Link];

namespace DataAccessLayer
{
public class ProductDAO

6|Page
{
public static List<Product> GetAll()
{
using var _db = new DbmotoRentalContext();
return _db.[Link](p => [Link]).ToList();
}

public Product? GetById(int id)


{
using var _db = new DbmotoRentalContext();
return _db.[Link](p => [Link] == id);
}

public Product? GetByName(string name)


{
using var _db = new DbmotoRentalContext();
return _db.[Link](p => [Link] == name);
}

public List<Product> Find(Expression<Func<Product, bool>> predicate)


{
using var _db = new DbmotoRentalContext();
return _db.[Link](predicate).ToList();
}

public Product Add(Product p)


{
using var _db = new DbmotoRentalContext();
_db.[Link](p);
_db.SaveChanges();
return p;

7|Page
}

public void Update(Product p)


{
using var _db = new DbmotoRentalContext();
_db.[Link](p);
_db.SaveChanges();
}

public void Delete(int id)


{
using var _db = new DbmotoRentalContext();
var entity = _db.[Link](id);
if (entity == null) return;
_db.[Link](entity);
_db.SaveChanges();
}
}
}

Step 04. The codes for [Link]:

8|Page
CÓ THỂ BỎ PHẦN TẠO [Link]
private static string? ReadConn()

// Đọc file ở thư mục chạy (bin\Debug\...)

var cfg = new ConfigurationBuilder()

.SetBasePath([Link])

.AddJsonFile("[Link]", optional: false, reloadOnChange: true)

.Build();

return [Link]("DBMotor");

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {

if (![Link])

var cs = ReadConn();

if ([Link](cs))

throw new InvalidOperationException("Missing connection string 'DBMotor'.");

[Link](cs);

9|Page
Activity 04: Write codes for the Repositories project

Step 01. On the Repositories project, add an interface named [Link] and write
codes as follows:
public interface IProductRepository
{
//void SaveProduct (Product c);
// void DeleteProduct(Product c);
//void UpdateProduct (Product c);
public List<Product> GetAll();
//Product GetProductById(int id);
}

public class ProductRepository: IProductRepository


{
public List<Product> GetAll() => [Link]();
}

Activity 05: Write codes for the Services project

Step 05. Write codes for class [Link] as follows:

10 | P a g e
public class ProductService

private readonly IProductRepository _repository;

public ProductService() => _repository = new ProductRepository();

public List<Product> GetAll ()

return _repository.GetAll();

Test với consoleapp

using Service;

using Bussiness;

internal class Program

private static void Main(string[] args)

[Link]("Hello, World!");

ProductService productService = new ProductService();

List<Product> products = [Link]();

foreach (Product product in products)

[Link](product);

11 | P a g e
}

Activity 04: Design UI and write codes for WPF project

12 | P a g e
Step 01. On the WPF project, design UI as follows:

 XAML code for [Link]

<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
xmlns:d="[Link]
xmlns:mc="[Link]
xmlns:local="clr-namespace:WPFApp"
mc:Ignorable="d"
Loaded="Window_Loaded"
WindowStartupLocation="CenterScreen"

13 | P a g e
Title="Product Management" Height="670" Width="710">
<Grid>
<Grid>
<[Link]>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="#0099FF" Offset="0"/>
<GradientStop Color="#FF347BDA" Offset="0.794"/>
<GradientStop Color="#FF60B1E7" Offset="1"/>
<GradientStop Color="#FF596FDD" Offset="0.309"/>
<GradientStop Color="#FF472FDE" Offset="0.484"/>
</LinearGradientBrush>
</[Link]>
<[Link]>
<RowDefinition Height="60"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="30"/>
</[Link]>

<[Link]>
<ColumnDefinition Width="119.415"/>
<ColumnDefinition Width="30.585"/>
<ColumnDefinition Width="47*"/>
<ColumnDefinition Width="513*"/>
</[Link]>

<Label x:Name="label" Content="Product Management" [Link]="2"


[Link]="0" FontSize="36" [Link]="2" HorizontalAlignment="Center"
Width="466"/>

<Label x:Name="label1" Margin ="2,2,2,2" Content="Product ID"


[Link]="0" [Link]="1" [Link]="2"/>
<TextBox x:Name="txtProductID" Margin ="4,4,4,4" [Link]="2"
[Link]="1" Text="" TextWrapping="Wrap" [Link]="2"
IsEnabled="False" />

<Label x:Name="label2" Margin ="2,2,2,2" [Link]="0" [Link]="2"


Content="Product Name" [Link]="2" />
<TextBox x:Name="txtProductName" Margin ="4,4,4,4" [Link]="2"
[Link]="2" Text="" TextWrapping="Wrap" [Link]="2" />

<Label x:Name="label8" Margin ="2,2,2,2" Content="Price" [Link]="0"


[Link]="3" [Link]="2"/>
<TextBox x:Name="txtPrice" Margin ="4,4,4,4" [Link]="2" [Link]="3"
Text="" TextWrapping="Wrap" [Link]="2" />

<Label x:Name="label3" Margin ="2,2,2,2" Content="Units In Stock"


[Link]="0" [Link]="4" [Link]="2"/>

14 | P a g e
<TextBox x:Name="txtUnitsInStock" Margin ="4,4,4,4" [Link]="2"
[Link]="4" Text="" TextWrapping="Wrap" [Link]="2" />

<Label x:Name="label4" Margin ="2,2,2,2" Content="Category"


[Link]="0" [Link]="5" [Link]="2"/>
<ComboBox x:Name="cboCategory" Margin ="4,4,4,4" [Link]="2"
[Link]="5" [Link]="2" />

<DataGrid x:Name="dgData" Margin ="4,4,4,63" [Link]="2"


[Link]="6" [Link]="2" SelectionChanged="dgData_SelectionChanged" />
<Button x:Name="btnCreate" Content="Create" HorizontalAlignment="Left"
Margin="29,365,0,16" [Link]="6" [Link]="2" Width="121"
Background="#FF0099FF" BorderBrush="White" Foreground="White"
[Link]="3" [Link]="1" Click="btnCreate_Click"/>
<Button x:Name="btnUpdate" Content="Update" [Link]="3"
HorizontalAlignment="Left" Margin="87,365,0,16" [Link]="6" Width="118"
Background="#FF1B7140" Foreground="White" [Link]="2"
RenderTransformOrigin="0.37,0.2" Click="btnUpdate_Click"/>
<Button x:Name="btnDelete" Content="Delete" [Link]="3"
HorizontalAlignment="Left" Margin="221,365,0,16" [Link]="6" [Link]="2"
Width="127" Foreground="White" Background="#FFA2AA3D"
Click="btnDelete_Click"/>

<Button x:Name="btnClose" Content="Close" [Link]="3"


HorizontalAlignment="Left" Margin="371,365,0,18" [Link]="6" [Link]="2"
Width="120" Background="#FFEF8F18" Foreground="White" Click="btnClose_Click"/>

</Grid>
</Grid>
</Window>

15 | P a g e
<Window x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
xmlns:d="[Link]
xmlns:mc="[Link]
xmlns:local="clr-namespace:WPFApp"
mc:Ignorable="d"
Title="LoginWindow" Height="450" Width="800"
WindowStartupLocation="CenterScreen"
WindowStyle="None"
Background="Transparent"
AllowsTransparency="True">
<Grid>
<Border CornerRadius="10"
BorderThickness="2"
Opacity="0.95">
<[Link]>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="#0099FF" Offset="0"/>
<GradientStop Color="#DA34AE" Offset="0.75"/>
<GradientStop Color="#FF60B1E7" Offset="1"/>
<GradientStop Color="#FF596FDD" Offset="0.309"/>
<GradientStop Color="#FF8C57CA" Offset="0.484"/>
</LinearGradientBrush>
</[Link]>
<[Link]>
<LinearGradientBrush StartPoint="0,1" EndPoint="1,0">
<GradientStop Color="#060531" Offset="0"/>
<GradientStop Color="#FF472FDE" Offset="1"/>
</LinearGradientBrush>

16 | P a g e
</[Link]>

<Grid>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center"
Height="82" VerticalAlignment="Top" Width="632">
<TextBlock Text="LOGIN WINDOW"
Foreground="White"
FontSize="28"
FontWeight="Medium"
FontFamily="Montserrat"
Cursor="Hand"
Margin="180,30,0,0" Width="377"
/>
</StackPanel>
<StackPanel
Orientation="Vertical"
Margin="82,102,82,68">
<TextBlock Text="Username"
Foreground="DarkGray"
FontSize="12"
FontWeight="Medium"
FontFamily="Montserrat"
Margin="0,35,0,0"/>
<TextBox x:Name="txtUser"
FontSize="13"
FontWeight="Medium"
FontFamily="Montserrat"
Foreground="White"
CaretBrush="LightGray"
BorderBrush="DarkGray"
BorderThickness="0,0,0,2"
Height="28"
VerticalContentAlignment="Center"
Margin="0,5,0,0"
>
<[Link]>
<LinearGradientBrush></LinearGradientBrush>
</[Link]>
</TextBox>

<TextBlock Text="Password"
Foreground="DarkGray"
FontSize="12"
FontWeight="Medium"
FontFamily="Montserrat"
Margin="0,15,0,0"/>
<PasswordBox x:Name="txtPass"
FontSize="13"
FontWeight="Medium"
FontFamily="Montserrat"
Foreground="White"

17 | P a g e
CaretBrush="LightGray"
BorderBrush="DarkGray"
BorderThickness="0,0,0,2"
Height="28"
VerticalContentAlignment="Center"
Margin="0,5,0,0">
<[Link]>
<LinearGradientBrush></LinearGradientBrush>
</[Link]>
</PasswordBox>
<Button x:Name="btnLogin"
BorderThickness="0"
Content="LOG IN"
Foreground="White"
FontSize="12"
FontFamily="Montserrat"
Cursor="Hand"
Margin="0,50,0,0"
Click="btnLogin_Click">
<[Link]>
<Style TargetType="Button">
<Setter Property="Background" Value="#0099FF"/>
<[Link]>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#28AEED"/>
</Trigger>
</[Link]>
</Style>
</[Link]>
<[Link]>
<ControlTemplate TargetType="Button">
<Border Width="150" Height="40"
CornerRadius="20"
Background="{TemplateBinding Background}">
<ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
</[Link]>

</Button>

</StackPanel>
<StackPanel>
<Button x:Name="btnCancel"
BorderThickness="0"
Content="CANCEL"
Foreground="White"
FontSize="12"
FontFamily="Montserrat"

18 | P a g e
Cursor="Hand"
Margin="20,350,20,0"
Click="btnCancel_Click">
<[Link]>
<Style TargetType="Button">
<Setter Property="Background" Value="LightSeaGreen"/>
<[Link]>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="SeaGreen"/>
</Trigger>
</[Link]>
</Style>
</[Link]>
<[Link]>
<ControlTemplate TargetType="Button">
<Border Width="150" Height="40"
CornerRadius="20"
Background="{TemplateBinding Background}">
<ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
</[Link]>

</Button>

</StackPanel>

</Grid>

</Border>
</Grid>
</Window>

Step 02. Right-click on the project | Add | New Item, select JavaScript JSON Configuration
File then rename to [Link], click Add and write contents as follows:
{
"ConnectionStrings": {
"MyStockDB": "Server=(local);uid=sa;pwd=1234567890;database=MyStore;"
}
}

Next, right-click on [Link] | Properties, select Copy if newer

Step 03. Add a reference to the WPF project to Services Project

19 | P a g e
Step 04. Write codes for [Link]:

The details for btnLogin_Click() function:

20 | P a g e
Step 05. Write codes for [Link]:

The functions in details:

21 | P a g e
22 | P a g e
23 | P a g e
24 | P a g e
25 | P a g e
Step 06. Open [Link] and then update XAML code as follows:
<Application x:Class="[Link]"
xmlns="[Link]
xmlns:x="[Link]
xmlns:local="clr-namespace:WPFApp"
StartupUri="[Link]">
<[Link]>

</[Link]>
</Application>

Activity 05: Run the WPFApp project and test all actions

26 | P a g e

You might also like