I'm a .Net beginner and I'm trying to create a simple EShop ASP.Net web application.
I've created a Class named FactorRepository and here is the code:
public class FactorRepository : IFactorRepository
{
private const string _connectionString = "ConntectionString";
ICartRepository _cartRepository;
IProductRepository _productRepository;
public FactorRepository(ICartRepository cartRepository, IProductRepository productRepository)
{
_cartRepository = cartRepository;
_productRepository = productRepository;
}
public Factor CreateFactor(int cartId, int customerId)
{
Factor factor = new Factor();
using (SqlConnection sql = new SqlConnection(_connectionString))
{
try
{
customerId = 1;
var cart = _cartRepository.GetCartBy(1);
int totalPrice = cart.TotalPrice;
DateTime createdDate = DateTime.Now.Date;
sql.Open();
SqlCommand command = sql.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = $"Insert into Factors (CustomerId, TotalPrice, CreatedDate) values ({customerId}, {totalPrice}, {createdDate})";
var reader = command.ExecuteReader();
if (reader.Read())
{
factor.CustomerId = int.Parse(reader["CustomerId"].ToString());
factor.TotalPrice = int.Parse(reader["TotalPrice"].ToString());
factor.CreatedDate = DateTime.Parse(reader["CreatedDate"].ToString());
}
sql.Close();
return factor;
}
catch (Exception)
{
throw;
}
}
}
}
Where am I going wrong and what is my problem/problems?
Try to add single quotes in dates '{createdDate}'
It would be better to use Command Parameter for passing value to avoid SQL Injection
command.CommandText = $"Insert into Factors (CustomerId, TotalPrice, CreatedDate) values ({customerId}, {totalPrice}, '{createdDate}')";