BuecherwurmAPI/Models/ItemModel.cs

115 lines
4.0 KiB
C#
Raw Normal View History

2020-06-02 12:23:21 +00:00
using System;
using System.Collections.Generic;
using BuecherwurmAPI.Models;
using Microsoft.Data.Sqlite;
using Microsoft.VisualBasic.CompilerServices;
namespace BuecherwurmAPI.Models
{
internal class ItemModel : IItemRepo
{
private SqliteConnection _dbConnection;
public ItemModel()
{
var connectionBuilder = new SqliteConnectionStringBuilder {DataSource = "LongWormMemory.db"};
_dbConnection = new SqliteConnection(connectionBuilder.ConnectionString);
_dbConnection.Open();
}
public bool IdExits(string table, long id)
{
using (var command = _dbConnection.CreateCommand())
{
command.Parameters.Add(new SqliteParameter("@Id", SqliteType.Integer)).Value = id;
// Certain parts of the query can't be filled with variables for security reasons.
switch (table)
{
case Tables.Table.Items:
command.CommandText = @"SELECT EXISTS(SELECT 0 FROM Items WHERE Id = @Id)";
break;
}
var dr = command.ExecuteReader();
long result = 0;
while (dr.Read())
{
result = (long) dr[0];
}
return result != 0;
}
}
public IEnumerable<Item> GetAllItems()
{
var items = new List<Item>();
// using automatically disposes the command after completion
using (var command = _dbConnection.CreateCommand())
{
command.CommandText = @"SELECT * FROM Items";
var dataReader = command.ExecuteReader();
while (dataReader.Read())
{
var returned = (long) dataReader["Returned"] == 1;
items.Add(new Item
{
ItemId = (int) dataReader["ItemId"],
BookId = (int) dataReader["BookId"]
});
}
}
return items;
}
public Item GetItemById(int id)
{
using (var command = _dbConnection.CreateCommand())
{
command.Parameters.Add(new SqliteParameter("@id", SqliteType.Integer)).Value = id;
command.CommandText = @"SELECT * FROM Items WHERE Id = @id";
var dataReader = command.ExecuteReader();
while (dataReader.Read())
{
var returned = (long) dataReader["Returned"] == 1;
var item = new Item
{
ItemId = (int) dataReader["ItemId"],
BookId = (int) dataReader["BookId"]
};
return item;
}
}
return null;
}
public Item NewItem(ItemPost itemPost)
2020-06-02 12:23:21 +00:00
{
using (var command = _dbConnection.CreateCommand())
{
//hier soll jetz der NewItem Command folgen. ein POST mit EingabeInfo {id} = "BookId"
command.CommandText = "INSERT INTO Item(BOOKID) VALUES (@item)";
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add(new SqliteParameter("@ITEMID", itemPost)
item;
2020-06-02 12:23:21 +00:00
return item;
}
}
public void DeleteItem(int itemId)
2020-06-02 12:23:21 +00:00
{
using (var command = _dbConnection.CreateCommand())
{
command.Parameters.Add(new SqliteParameter("@id", SqliteType.Integer)).Value = itemId;
2020-06-02 12:23:21 +00:00
//hier soll jetz der NewItem Command folgen. ein POST mit EingabeInfo {id} = "BookId"
command.CommandText = @"SELECT * FROM Items WHERE ItemId = @id";
}
}
}
}