Compare commits

..

2 Commits

21 changed files with 418 additions and 14 deletions

View File

@ -0,0 +1,12 @@
using DataAccess.Models;
namespace DataAccess.Data;
public interface IUserData
{
Task<IEnumerable<UserModel>> GetUsers();
Task<UserModel?> GetUser(int id);
Task InsertUser(UserModel user);
Task UpdateUser(UserModel user);
Task DeleteUser(int id);
}

View File

@ -0,0 +1,43 @@
using DataAccess.DbAccess;
using DataAccess.Models;
namespace DataAccess.Data;
public class UserData : IUserData
{
private readonly ISqlDataAccess _db;
public UserData(ISqlDataAccess db)
{
_db = db;
}
public Task<IEnumerable<UserModel>> GetUsers()
{
return _db.LoadData<UserModel, dynamic>("dbo.spUser_GetAll", new { });
}
public async Task<UserModel?> GetUser(int id)
{
IEnumerable<UserModel> results = await _db.LoadData<UserModel, dynamic>(
"dbo.spUser_Get",
new { Id = id });
return results.FirstOrDefault();
}
public Task InsertUser(UserModel user)
{
return _db.SaveData("dbo.spUser_Insert", new { user.FirstName, user.LastName });
}
public Task UpdateUser(UserModel user)
{
return _db.SaveData("dbo.spUser_Update", user);
}
public Task DeleteUser(int id)
{
return _db.SaveData("dbo.spUser_Delete", new { Id = id });
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,33 @@
namespace DataAccess.DbAccess;
/// <summary>
/// Stellt Methoden zur Ausführung von CRUD-Operationen bereit.
/// </summary>
public interface ISqlDataAccess
{
/// <summary>
/// Liest Daten aus der Datenbank (Read Operationen).
/// </summary>
/// <typeparam name="TData">Typ der Objekte die zurückgegeben werden.</typeparam>
/// <typeparam name="TParam">Typ des Objekts das die Parameter für die SQL-Query enthält.</typeparam>
/// <param name="storedProcedureName">Name der StoredProcedure die ausgeführt werden soll.</param>
/// <param name="parameters">Das Objekt das die Parameter enthält.</param>
/// <param name="connectionId">Der Name des ConnectionStrings der für die Verbindung verwendet werden soll.</param>
/// <returns>Die Ergebnisse der Anfrage.</returns>
Task<IEnumerable<TData>> LoadData<TData, TParam>(
string storedProcedureName,
TParam parameters,
string connectionId = "Default");
/// <summary>
/// Führt eine SQL-Anfrage aus, die keinen Rückgabewert hat (Create, Update und Delete Operationen).
/// </summary>
/// <typeparam name="TParam">Typ des Objekts das die Parameter für die SQL-Query enthält.</typeparam>
/// <param name="storedProcedureName">Name der StoredProcedure die ausgeführt werden soll.</param>
/// <param name="parameters">Das Objekt das die Parameter enthält.</param>
/// <param name="connectionId">Der Name des ConnectionStrings der für die Verbindung verwendet werden soll.</param>
Task SaveData<TParam>(
string storedProcedureName,
TParam parameters,
string connectionId = "Default");
}

View File

@ -0,0 +1,38 @@
using Dapper;
using Microsoft.Extensions.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace DataAccess.DbAccess;
public class SqlDataAccess : ISqlDataAccess
{
private readonly IConfiguration _config;
public SqlDataAccess(IConfiguration config)
{
_config = config;
}
public async Task<IEnumerable<TData>> LoadData<TData, TParam>(
string storedProcedureName,
TParam parameters,
string connectionId = "Default")
{
using IDbConnection connection = new SqlConnection(_config.GetConnectionString(connectionId));
return await connection.QueryAsync<TData>(storedProcedureName, parameters,
commandType: CommandType.StoredProcedure);
}
public async Task SaveData<TParam>(
string storedProcedureName,
TParam parameters,
string connectionId = "Default")
{
using IDbConnection connection = new SqlConnection(_config.GetConnectionString(connectionId));
await connection.ExecuteAsync(storedProcedureName, parameters,
commandType: CommandType.StoredProcedure);
}
}

View File

@ -0,0 +1,8 @@
namespace DataAccess.Models;
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
}

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<Name>GottfriedsNackenDB</Name>
<SchemaVersion>2.0</SchemaVersion>
<ProjectVersion>4.1</ProjectVersion>
<ProjectGuid>{79f8ac31-e467-4f7c-ac3b-cfadc3290750}</ProjectGuid>
<DSP>Microsoft.Data.Tools.Schema.Sql.Sql130DatabaseSchemaProvider</DSP>
<OutputType>Database</OutputType>
<RootPath>
</RootPath>
<RootNamespace>GottfriedsNackenDB</RootNamespace>
<AssemblyName>GottfriedsNackenDB</AssemblyName>
<ModelCollation>1033, CI</ModelCollation>
<DefaultFileStructure>BySchemaAndSchemaType</DefaultFileStructure>
<DeployToDatabase>True</DeployToDatabase>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetLanguage>CS</TargetLanguage>
<AppDesignerFolder>Properties</AppDesignerFolder>
<SqlServerVerification>False</SqlServerVerification>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseSet>True</TargetDatabaseSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\Release\</OutputPath>
<BuildScriptName>$(MSBuildProjectName).sql</BuildScriptName>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\Debug\</OutputPath>
<BuildScriptName>$(MSBuildProjectName).sql</BuildScriptName>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">11.0</VisualStudioVersion>
<!-- Default to the v11.0 targets path if the targets file for the current VS version is not found -->
<SSDTExists Condition="Exists('$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets')">True</SSDTExists>
<VisualStudioVersion Condition="'$(SSDTExists)' == ''">11.0</VisualStudioVersion>
</PropertyGroup>
<Import Condition="'$(SQLDBExtensionsRefPath)' != ''" Project="$(SQLDBExtensionsRefPath)\Microsoft.Data.Tools.Schema.SqlTasks.targets" />
<Import Condition="'$(SQLDBExtensionsRefPath)' == ''" Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\SSDT\Microsoft.Data.Tools.Schema.SqlTasks.targets" />
<ItemGroup>
<Folder Include="Properties" />
<Folder Include="dbo" />
<Folder Include="dbo\Tables" />
<Folder Include="dbo\StoredProcedures" />
</ItemGroup>
<ItemGroup>
<Build Include="dbo\Tables\User.sql" />
<Build Include="dbo\StoredProcedures\spUser_GetAll.sql" />
<Build Include="dbo\StoredProcedures\spUser_Get.sql" />
<Build Include="dbo\StoredProcedures\spUser_Delete.sql" />
<Build Include="dbo\StoredProcedures\spUser_Insert.sql" />
<Build Include="dbo\StoredProcedures\spUser_Update.sql" />
</ItemGroup>
<ItemGroup>
<None Include="GottfriedsNackenDB.publish.xml" />
</ItemGroup>
<ItemGroup>
<PostDeploy Include="Script.PostDeployment.sql" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,10 @@
/* Wird nur ausgeführt, wenn es keine Einträge in [dbo].[User] */
IF not exists (SELECT 1 FROM [dbo].[User])
BEGIN
INSERT INTO [dbo].[User] (FirstName, LastName)
VALUES
('Gottfried Wilhelm', 'Leibniz'),
('Albert', 'Einstein'),
('Curry', 'Wurst'),
('Brat', 'Wurst')
END

View File

@ -0,0 +1,8 @@
CREATE PROCEDURE [dbo].[spUser_Delete]
@Id int
AS
BEGIN
DELETE
FROM [dbo].[User]
WHERE Id = @Id;
END

View File

@ -0,0 +1,8 @@
CREATE PROCEDURE [dbo].[spUser_Get]
@Id int
AS
BEGIN
SELECT Id, FirstName, LastName
FROM [dbo].[User]
WHERE Id = @Id;
END

View File

@ -0,0 +1,6 @@
CREATE PROCEDURE [dbo].[spUser_GetAll]
AS
BEGIN
SELECT Id, FirstName, LastName
FROM [dbo].[User];
END

View File

@ -0,0 +1,8 @@
CREATE PROCEDURE [dbo].[spUser_Insert]
@FirstName nvarchar(50),
@LastName nvarchar(50)
AS
BEGIN
INSERT INTO [dbo].[User] (FirstName, LastName)
VALUES (@FirstName, @LastName);
END

View File

@ -0,0 +1,10 @@
CREATE PROCEDURE [dbo].[spUser_Update]
@Id int,
@FirstName nvarchar(50),
@LastName nvarchar(50)
AS
BEGIN
UPDATE [dbo].[User]
SET FirstName = @FirstName, LastName = @LastName
WHERE Id = @Id;
END

View File

@ -0,0 +1,6 @@
CREATE TABLE [dbo].[User]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[FirstName] NVARCHAR(50) NOT NULL,
[LastName] NVARCHAR(50) NOT NULL
)

View File

@ -5,7 +5,11 @@ VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GottfriedsNackenWebseite", "GottfriedsNackenWebseite\GottfriedsNackenWebseite.csproj", "{464DD643-DAD9-4E16-BB24-36F789ED4C15}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GottfriedsNackenWebseite", "GottfriedsNackenWebseite\GottfriedsNackenWebseite.csproj", "{464DD643-DAD9-4E16-BB24-36F789ED4C15}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GottfriedsNackenUtility", "GottfriedsNackenUtility\GottfriedsNackenUtility.csproj", "{0122762F-9961-4D28-8AA9-0D6AE7630208}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GottfriedsNackenUtility", "GottfriedsNackenUtility\GottfriedsNackenUtility.csproj", "{0122762F-9961-4D28-8AA9-0D6AE7630208}"
EndProject
Project("{00D1A9C2-B5F0-4AF3-8072-F6C62B433612}") = "GottfriedsNackenDB", "GottfriedsNackenDB\GottfriedsNackenDB.sqlproj", "{79F8AC31-E467-4F7C-AC3B-CFADC3290750}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataAccess", "DataAccess\DataAccess.csproj", "{023715EE-C9DB-417F-9B77-28BF48A30D41}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -21,6 +25,16 @@ Global
{0122762F-9961-4D28-8AA9-0D6AE7630208}.Debug|Any CPU.Build.0 = Debug|Any CPU {0122762F-9961-4D28-8AA9-0D6AE7630208}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0122762F-9961-4D28-8AA9-0D6AE7630208}.Release|Any CPU.ActiveCfg = Release|Any CPU {0122762F-9961-4D28-8AA9-0D6AE7630208}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0122762F-9961-4D28-8AA9-0D6AE7630208}.Release|Any CPU.Build.0 = Release|Any CPU {0122762F-9961-4D28-8AA9-0D6AE7630208}.Release|Any CPU.Build.0 = Release|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Release|Any CPU.Build.0 = Release|Any CPU
{79F8AC31-E467-4F7C-AC3B-CFADC3290750}.Release|Any CPU.Deploy.0 = Release|Any CPU
{023715EE-C9DB-417F-9B77-28BF48A30D41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{023715EE-C9DB-417F-9B77-28BF48A30D41}.Debug|Any CPU.Build.0 = Debug|Any CPU
{023715EE-C9DB-417F-9B77-28BF48A30D41}.Release|Any CPU.ActiveCfg = Release|Any CPU
{023715EE-C9DB-417F-9B77-28BF48A30D41}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -18,6 +18,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DataAccess\DataAccess.csproj" />
<ProjectReference Include="..\GottfriedsNackenUtility\GottfriedsNackenUtility.csproj" /> <ProjectReference Include="..\GottfriedsNackenUtility\GottfriedsNackenUtility.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,96 @@
@page "/databasetest"
@using DataAccess.Data
@using DataAccess.Models
@inject IUserData _userData
<PageTitle>Database Test</PageTitle>
<MudContainer MaxWidth="MaxWidth.Small">
<MudTable Items="@_users" Hover="true" Breakpoint="Breakpoint.Sm" Loading="_loading">
<ToolBarContent>
<MudText Typo="Typo.h6">Nutzer</MudText>
<MudSpacer />
<MudIconButton Icon="@Icons.Material.Filled.Refresh" OnClick="RefreshUserList" />
</ToolBarContent>
<HeaderContent>
<MudTh>Id</MudTh>
<MudTh>First Name</MudTh>
<MudTh>Last Name</MudTh>
<MudTh/>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Nr">@context.Id</MudTd>
<MudTd DataLabel="First Name">@context.FirstName</MudTd>
<MudTd DataLabel="Last Name">@context.LastName</MudTd>
<MudTd>
<MudIconButton Icon="@Icons.Material.Filled.Delete" OnClick="() => DeleteUser(context)" />
</MudTd>
</RowTemplate>
<PagerContent>
<MudTablePager/>
</PagerContent>
</MudTable>
<MudPaper Class="pa-4 mt-2">
<MudForm @bind-IsValid="_newUserValid" >
<MudText Typo="Typo.h4">Neuen Nutzer erstellen:</MudText>
<MudTextField T="string" Label="Vorname" @bind-Value="_newUser.FirstName" Immediate="true" Required="true" RequiredError="Vorname muss angegeben werden!"/>
<MudTextField T="string" Label="Nachname" @bind-Value="_newUser.LastName" Immediate="true" Required="true" RequiredError="Nachname muss angegeben werden!"/>
<MudButton Class="mt-2" Variant="Variant.Filled" Color="Color.Primary" Disabled="!_newUserValid" OnClick="AddUser">Hinzufügen</MudButton>
</MudForm>
</MudPaper>
</MudContainer>
@code {
private bool _newUserValid;
private UserModel _newUser = new();
private bool _loading;
private IEnumerable<UserModel> _users = Enumerable.Empty<UserModel>();
protected override async Task OnInitializedAsync()
{
await RefreshUserList();
await base.OnInitializedAsync();
}
private async Task RefreshUserList()
{
_loading = true;
try
{
_users = await _userData.GetUsers();
}
catch (Exception e)
{
Console.WriteLine($"Failed to load users. Exception: {e}");
}
_loading = false;
}
private async Task AddUser()
{
await _userData.InsertUser(_newUser);
await RefreshUserList();
_newUser = new UserModel();
}
private async Task DeleteUser(UserModel user)
{
await _userData.DeleteUser(user.Id);
await RefreshUserList();
}
}

View File

@ -1,3 +1,5 @@
using DataAccess.Data;
using DataAccess.DbAccess;
using GottfriedsNackenWebseite.Data; using GottfriedsNackenWebseite.Data;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web;
@ -11,6 +13,9 @@ builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>(); builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddMudServices(); builder.Services.AddMudServices();
builder.Services.AddSingleton<ISqlDataAccess, SqlDataAccess>();
builder.Services.AddSingleton<IUserData, UserData>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

View File

@ -23,6 +23,9 @@
<MudNavLink Href="numberle" Match=NavLinkMatch.Prefix> <MudNavLink Href="numberle" Match=NavLinkMatch.Prefix>
Nacken Numberle Nacken Numberle
</MudNavLink> </MudNavLink>
<MudNavLink Href="databasetest" Match=NavLinkMatch.Prefix>
Datenbank Test
</MudNavLink>
</MudNavMenu> </MudNavMenu>
@* @*
<div class="top-row ps-3 navbar navbar-dark"> <div class="top-row ps-3 navbar navbar-dark">

View File

@ -5,5 +5,5 @@
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
} },
} }

View File

@ -5,5 +5,8 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"ConnectionStrings": {
"Default": "PLACEHOLDER"
}
} }