Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

using-System

The document contains a C# implementation of an inventory management system focusing on category management. It includes a CategoryService for CRUD operations, a GenericRepository for database interactions using Dapper, and a CategoryController for API endpoints. The structure follows a layered architecture with services, repositories, and controllers for handling category data.
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)
6 views

using-System

The document contains a C# implementation of an inventory management system focusing on category management. It includes a CategoryService for CRUD operations, a GenericRepository for database interactions using Dapper, and a CategoryController for API endpoints. The structure follows a layered architecture with services, repositories, and controllers for handling category data.
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/ 6

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inventory_Dapper.Model;
using Inventory_Dapper.Repository;

namespace Inventory_Dapper.Services
{
public class CategoryService
{
CategoryRepository _categoryRepository;

public CategoryModel GetCategoryById(int id)


{
_categoryRepository = new CategoryRepository();
return _categoryRepository.GetById(id);
}

// Get all categories


public IEnumerable<CategoryModel> GetAllCategories()
{
CategoryRepository _categoryRepository = new CategoryRepository();
return _categoryRepository.GetAll();
}

public bool AddCategory(CategoryModel category)


{
_categoryRepository = new CategoryRepository();
return _categoryRepository.Add(category);
}

public bool UpdateCategory(CategoryModel category)


{
_categoryRepository = new CategoryRepository();
return _categoryRepository.Update(category);
}

public bool DeleteCategory(CategoryModel category)


{
_categoryRepository = new CategoryRepository();
return _categoryRepository.Delete(category);
}

}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inventory_Dapper.Model;
using MyFirstDapper.Repository;

namespace Inventory_Dapper.Repository
{
public class CategoryRepository : GenericRepository<CategoryModel>
{

}
}

using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyFirstDapper.Repository
{
public class GenericRepository<T> : IgenericRepository<T> where T : class
{
IDbConnection _connection;
readonly string connectionString = "Server=LAPTOP-0QGDR041;
Database=InventoryDb; Trusted_Connection=True; MultipleActiveResultSets=True;";
public GenericRepository()
{
_connection = new SqlConnection(connectionString);
}

public T GetById(int id)


{
return null;
}

public bool Add(T entity)


{
string tableName = GetTableName();
string columns = GetColumnNames(true);
string values = GetColumnValues(true);
string query = $"INSERT INTO {tableName} ({columns}) VALUES ({values})";

int affectedRows = 0;

affectedRows = _connection.Execute(query, entity);


return affectedRows == 1;
}

public bool Update(T entity)


{
string tableName = GetTableName();
string keyColumn = GetKeyColumn();

try
{
var properties = typeof(T).GetProperties()
.Where(p => p.GetCustomAttribute<KeyAttribute>() == null) // Exclude key
column from SET
.ToList();

if (!properties.Any())
throw new InvalidOperationException("No columns to update. Ensure the
entity has properties other than the key.");

var setClause = string.Join(", ", properties.Select(p => $"{p.Name} =


@{p.Name}"));
var sql = $"UPDATE {tableName} SET {setClause} WHERE {keyColumn} =
@{keyColumn}";

var result = _connection.Execute(sql, entity);


return result > 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error updating entity: {ex.Message}");
return false;
}
}

public bool Delete(T entity)


{
string tableName = GetTableName();
string keyColumn = GetKeyColumn();

try
{
var sql = $"DELETE FROM {tableName} WHERE {keyColumn} =
@{keyColumn}";
var result = _connection.Execute(sql, entity);
return result > 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting entity: {ex.Message}");
return false;
}
}
//Get all Data
public IEnumerable<T> GetAll()
{
string tableName = GetTableName();
string query = $"SELECT * FROM {tableName}";
return _connection.Query<T>(query);
}

// Function on getting Name


public string GetTableName()
{
string tableName = "";
var type = typeof(T);
var tableAttr = type.GetCustomAttribute<TableAttribute>();
if (tableAttr != null)
{
tableName = tableAttr.Name;

return tableName;
}

//Function Column
public string GetColumnNames(bool excludeKey = false)
{
string columnNames = "";
var type = typeof(T);
var columns = string.Join(", ", type.GetProperties()
.Where(p => !excludeKey || !p.IsDefined(typeof(KeyAttribute)))
.Select(p =>
{
var columnAttr = p.GetCustomAttribute<ColumnAttribute>();
return columnAttr != null ? columnAttr.Name : p.Name;

}
));
return columns;

public string GetColumnValues(bool excludeKey = false)


{
var columnValues = typeof(T).GetProperties()
.Where(p => !excludeKey || p.GetCustomAttribute(typeof(KeyAttribute)) == null);
var values = string.Join(", ", columnValues.Select(p =>
{
return $"@{p.Name}";
}));

return values;
}

public string GetKeyColumn()


{
var type = typeof(T);
var keyProperty = type.GetProperties()
.FirstOrDefault(p => p.GetCustomAttribute<KeyAttribute>() !=
null);

return keyProperty?.Name ?? throw new InvalidOperationException("No key


column found.");
}

}
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFirstDapper.Repository
{
public interface IgenericRepository<T> where T : class
{
T GetById(int id);

bool Add(T entity);


bool Update(T entity);
bool Delete(T entity);
IEnumerable<T> GetAll();
}
}

using Inventory_Dapper.Model;
using Inventory_Dapper.Repository;
using Inventory_Dapper.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Inventory_SystemAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CategoryController : ControllerBase
{
CategoryRepository _categoryRepository;

[HttpGet]
public ActionResult<IEnumerable<CategoryModel>> GetAllCategories()
{
CategoryService _categoryService = new CategoryService();
var categories = _categoryService.GetAllCategories();
return Ok(categories);
}

[HttpPost]
public bool AddCategory(CategoryModel category)
{
CategoryService _categoryService = new CategoryService();
_categoryService.AddCategory(category);
return (true);
}

[HttpPut]
public bool UpdateCategory(CategoryModel category)
{
CategoryService _categoryService = new CategoryService();
_categoryService.UpdateCategory(category);
return (true);
}

[HttpDelete]
public bool DeleteCategory(CategoryModel category) {
CategoryService _categoryService = new CategoryService();
_categoryService.DeleteCategory(category);
return (true);
}
}
}

You might also like