Compare commits

...

2 Commits

Author SHA1 Message Date
Maciej Maciejewski
fc8ac5d51d Added transaction object, crud class and controller for transactions 2024-05-05 22:08:27 +02:00
Maciej Maciejewski
c94363b790 zmiany do testów rest api - swagger 2024-04-26 21:24:17 +02:00
15 changed files with 638 additions and 61 deletions

12
.config/dotnet-tools.json Normal file
View File

@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.4",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Mvc; using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate.Products; using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server;
using System.Collections.Generic;
namespace FirmTracker_Server.Controllers namespace FirmTracker_Server.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
@ -16,7 +14,12 @@ namespace FirmTracker_Server.Controllers
} }
// POST: api/Products // POST: api/Products
/// <summary>
/// Creates a new product.
/// </summary>
[HttpPost] [HttpPost]
[ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request
public IActionResult CreateProduct([FromBody] Product product) public IActionResult CreateProduct([FromBody] Product product)
{ {
try try
@ -32,6 +35,8 @@ namespace FirmTracker_Server.Controllers
// GET: api/Products/5 // GET: api/Products/5
[HttpGet("{id}")] [HttpGet("{id}")]
[ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request
public IActionResult GetProduct(int id) public IActionResult GetProduct(int id)
{ {
var product = _productCrud.GetProduct(id); var product = _productCrud.GetProduct(id);
@ -42,6 +47,8 @@ namespace FirmTracker_Server.Controllers
// PUT: api/Products/5 // PUT: api/Products/5
[HttpPut("{id}")] [HttpPut("{id}")]
[ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request
public IActionResult UpdateProduct(int id, [FromBody] Product product) public IActionResult UpdateProduct(int id, [FromBody] Product product)
{ {
if (id != product.Id) if (id != product.Id)
@ -60,6 +67,8 @@ namespace FirmTracker_Server.Controllers
// DELETE: api/Products/5 // DELETE: api/Products/5
[HttpDelete("{id}")] [HttpDelete("{id}")]
[ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request
public IActionResult DeleteProduct(int id) public IActionResult DeleteProduct(int id)
{ {
try try
@ -75,10 +84,44 @@ namespace FirmTracker_Server.Controllers
// GET: api/Products // GET: api/Products
[HttpGet] [HttpGet]
[ProducesResponseType(200)] // Created
[ProducesResponseType(400)] // Bad Request
public IActionResult GetAllProducts() public IActionResult GetAllProducts()
{ {
var products = _productCrud.GetAllProducts(); var products = _productCrud.GetAllProducts();
return Ok(products); return Ok(products);
} }
[HttpPost("CalculateTotalPrice")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
public IActionResult CalculateTotalPrice([FromBody] ProductOrder[] orders)
{
decimal totalPrice = 0;
decimal discount = 0;
foreach (var order in orders)
{
discount = order.Discount;
var product = _productCrud.GetProduct(order.ProductId);
if (product == null)
{
return BadRequest($"Product with ID {order.ProductId} not found.");
}
totalPrice += product.Price * order.Quantity;
}
// Apply discount
decimal discountAmount = totalPrice * (discount / 100);
totalPrice -= discountAmount;
return Ok(new { TotalPrice = totalPrice });
}
public class ProductOrder
{
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal Discount { get; set; }
}
} }
} }

View File

@ -0,0 +1,100 @@
using Microsoft.AspNetCore.Mvc;
using FirmTracker_Server.nHibernate.Transactions;
using FirmTracker_Server;
using System.Collections.Generic;
namespace FirmTracker_Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TransactionController : ControllerBase
{
private readonly TransactionCRUD _transactionCRUD;
public TransactionController()
{
_transactionCRUD = new TransactionCRUD();
}
// POST: api/Transaction
/// <summary>
/// Creates a new transaction.
/// </summary>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult CreateTransaction([FromBody] Transaction transaction)
{
try
{
_transactionCRUD.AddTransaction(transaction);
return CreatedAtAction(nameof(GetTransaction), new { id = transaction.Id }, transaction);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// GET: api/Transaction/5
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetTransaction(int id)
{
var transaction = _transactionCRUD.GetTransaction(id);
if (transaction == null)
return NotFound();
return Ok(transaction);
}
// PUT: api/Transaction/5
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult UpdateTransaction(int id, [FromBody] Transaction transaction)
{
if (id != transaction.Id)
return BadRequest("Transaction ID mismatch");
try
{
_transactionCRUD.UpdateTransaction(transaction);
return NoContent();
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
// DELETE: api/Transaction/5
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult DeleteTransaction(int id)
{
try
{
_transactionCRUD.DeleteTransaction(id);
return NoContent();
}
catch (Exception ex)
{
return NotFound(ex.Message);
}
}
// GET: api/Transaction
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult GetAllTransactions()
{
var transactions = _transactionCRUD.GetAllTransactions();
return Ok(transactions);
}
}
}

View File

@ -5,8 +5,13 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>FirmTracker_Server</RootNamespace> <RootNamespace>FirmTracker_Server</RootNamespace>
<UserSecretsId>08986e21-848b-485a-a219-03e2dc6041e4</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Content Include="Properties\launchSettings.json" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentNHibernate" Version="3.3.0" /> <PackageReference Include="FluentNHibernate" Version="3.3.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.18" />
@ -16,4 +21,31 @@
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" /> <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="Properties\launchSettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -4,33 +4,71 @@ using NHibernate.Dialect;
using NHibernate.Driver; using NHibernate.Driver;
using FirmTracker_Server.Controllers; using FirmTracker_Server.Controllers;
using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Products;
using FirmTracker_Server.nHibernate;
namespace FirmTracker_Server namespace FirmTracker_Server
{ {
public class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
string appDirectory = Directory.GetCurrentDirectory();
string configFilePath = Path.Combine(appDirectory, "appsettings.json");
string connectionString = "";
if (File.Exists(configFilePath))
{
var config = new ConfigurationBuilder()
.AddJsonFile(configFilePath)
.Build();
var connectionstringsection = config.GetSection("AppSettings:ConnectionString");
connectionString = connectionstringsection.Value;
SessionFactory.Init(connectionString);
}
else
{
Console.WriteLine($"The configuration file '{configFilePath}' was not found.");
}
// Add services to the container.
TestClass test = new TestClass(); TestClass test = new TestClass();
test.AddTestProduct(); test.AddTestProduct();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
var app = builder.Build(); var app = builder.Build();
var configSwagger = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) var port = configSwagger.GetValue<int>("Port", 5075);
var port2 = configSwagger.GetValue<int>("Port", 7039);
app.Urls.Add($"http://*:{port}");
app.Urls.Add($"https://*:{port2}");
try
{ {
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(); app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"/swagger/v1/swagger.json", "FirmTracker - TEST");
c.RoutePrefix = "swagger";
});
Console.WriteLine("uruchomiono swaggera");
app.UseHttpsRedirection();
}
catch (Exception ex)
{
Console.WriteLine("Nie uda³o siê uruchomiæ swaggera");
} }
app.UseHttpsRedirection();
app.UseAuthorization(); app.UseAuthorization();
@ -38,9 +76,9 @@ namespace FirmTracker_Server
app.MapControllers(); app.MapControllers();
var configuration = new Configuration(); var configuration = new Configuration();
app.Run(); app.Run();
} }
} }
} }

63
Properties/Resources.Designer.cs generated Normal file
View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FirmTracker_Server.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FirmTracker_Server.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

101
Properties/Resources.resx Normal file
View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,4 +1,34 @@
{ {
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5045"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7039;http://localhost:5045"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
},
"$schema": "https://json.schemastore.org/launchsettings.json", "$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": { "iisSettings": {
"windowsAuthentication": false, "windowsAuthentication": false,
@ -7,35 +37,5 @@
"applicationUrl": "http://localhost:17940", "applicationUrl": "http://localhost:17940",
"sslPort": 44326 "sslPort": 44326
} }
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5045",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7039;http://localhost:5045",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
} }
} }

View File

@ -1,4 +1,5 @@
using FirmTracker_Server.nHibernate; using FirmTracker_Server.Controllers;
using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products; using FirmTracker_Server.nHibernate.Products;
using NHibernate; using NHibernate;
@ -8,21 +9,41 @@ namespace FirmTracker_Server
{ {
public void AddTestProduct() public void AddTestProduct()
{ {
SessionFactory.Init("Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;"); // SessionFactory.Init(ConnectionString);
var product = new nHibernate.Products.Product var product = new nHibernate.Products.Product
{ {
Name = "Test Product2", Name = "Produkt 1",
Description = "This is a test product", Description = "testowy produkt",
Price = 11.99m, Price = 11.50m,
Type = 0, // Goods Type = 1,
Availability = true Availability = 5
};
var product2 = new nHibernate.Products.Product
{
Name = "Usluga 1",
Description = "testowa usluga",
Price = 1120.00m,
Type = 0,
Availability = 0
};
var transaction1 = new nHibernate.Transactions.Transaction
{
Date = DateTime.Now,
Description = "testowa transakcja",
Discount = 10,
EmployeeId = 1,
PaymentType = "Karta kredytowa",
Products = new List<Product> { product, product2 }
}; };
try try
{ {
FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD(); FirmTracker_Server.nHibernate.Products.ProductCRUD crud = new ProductCRUD();
FirmTracker_Server.nHibernate.Transactions.TransactionCRUD transactionCrud = new nHibernate.Transactions.TransactionCRUD();
crud.AddProduct(product); crud.AddProduct(product);
crud.AddProduct(product2);
transactionCrud.AddTransaction(transaction1);
} }
catch(Exception ex) catch(Exception ex)
{ {

View File

@ -1,9 +1,29 @@
{ {
"Logging": { "AppSettings": {
"LogLevel": { "ConnectionString": "Server=localhost;Database=FirmTrackerDB;User Id=sa;Password=Rap45tro2;",
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}, },
"AllowedHosts": "*" "profiles": {
} "http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5045"
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7039"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger"
}
}
}

View File

@ -1,4 +1,6 @@
namespace FirmTracker_Server.nHibernate.Products using System.Text.Json.Serialization;
namespace FirmTracker_Server.nHibernate.Products
{ {
public class Product public class Product
{ {
@ -7,6 +9,6 @@
public virtual string Description { get; set; } public virtual string Description { get; set; }
public virtual decimal Price { get; set; } public virtual decimal Price { get; set; }
public virtual int Type { get; set; } // 0 for service, 1 for goods public virtual int Type { get; set; } // 0 for service, 1 for goods
public virtual bool Availability { get; set; } public virtual int Availability { get; set; }
} }
} }

View File

@ -25,7 +25,12 @@ namespace FirmTracker_Server.nHibernate
.Database(MsSqlConfiguration.MsSql2012 .Database(MsSqlConfiguration.MsSql2012
.ConnectionString(c => c.Is(connectionString)) .ConnectionString(c => c.Is(connectionString))
.ShowSql()) .ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Products.ProductMapping>()) .Mappings(m =>
{
m.FluentMappings
.AddFromAssemblyOf<Products.ProductMapping>()
.AddFromAssemblyOf<Transactions.TransactionMapping>();
})
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //SchemaUpdate . Execute dla only update
.BuildSessionFactory(); .BuildSessionFactory();
} }

View File

@ -0,0 +1,21 @@
using FirmTracker_Server.nHibernate.Products;
using System.Text.Json.Serialization;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class Transaction
{
public virtual int Id { get; set; }
public virtual DateTime Date { get; set; }
public virtual int EmployeeId { get; set; }
public virtual IList<Product> Products { get; set; } = new List<Product>();
public virtual string PaymentType { get; set; }
public virtual int Discount { get; set; }
public virtual string Description { get; set; }
public Transaction()
{
Products = new List<Product>();
}
}
}

View File

@ -0,0 +1,95 @@
using FirmTracker_Server.nHibernate;
using FirmTracker_Server.nHibernate.Products;
using NHibernate;
using System.Collections.Generic;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Http.HttpResults;
using FirmTracker_Server.nHibernate.Transactions;
using NHibernate.Linq;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionCRUD
{
public void AddTransaction(Transaction transaction)
{
using (var session = SessionFactory.OpenSession())
using (var sessionTransaction = session.BeginTransaction())
{
try
{
session.Save(transaction);
sessionTransaction.Commit();
}
catch
{
sessionTransaction.Rollback();
throw;
}
}
}
public Transaction GetTransaction(int transactionId)
{
using (var session = SessionFactory.OpenSession())
{
var transaction = session.Query<Transaction>()
.Fetch(t => t.Products)
.FirstOrDefault(t => t.Id == transactionId);
return transaction;
}
}
public void UpdateTransaction(Transaction transaction)
{
using (var session = SessionFactory.OpenSession())
using (var t = session.BeginTransaction())
{
try
{
session.Update(transaction);
t.Commit();
}
catch
{
t.Rollback();
throw;
}
}
}
public void DeleteTransaction(int transactionId)
{
using (var session = SessionFactory.OpenSession())
using (var t = session.BeginTransaction())
{
try
{
var transaction = session.Get<Product>(transactionId);
if (transaction != null)
{
session.Delete(transaction);
t.Commit();
}
}
catch
{
t.Rollback();
throw;
}
}
}
public IList<Transaction> GetAllTransactions()
{
using (var session = SessionFactory.OpenSession())
{
var transactions = session.Query<Transaction>()
.FetchMany(t => t.Products)
.ToList();
return transactions;
}
}
}
}

View File

@ -0,0 +1,24 @@
using FluentNHibernate.Mapping;
namespace FirmTracker_Server.nHibernate.Transactions
{
public class TransactionMapping:ClassMap<Transaction>
{
public TransactionMapping()
{
Table("Transactions");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Date);
Map(x => x.EmployeeId);
Map(x => x.PaymentType);
Map(x => x.Discount);
Map(x => x.Description);
HasManyToMany(x => x.Products)
.Table("TransactionProducts")
.ParentKeyColumn("TransactionId")
.ChildKeyColumn("ProductId")
.Cascade.All();
}
}
}