So I’m trying to add in the database certain items into a user stock, and I get this problem
For context I’m using .netcore web api, entityframework, identity and sql server on backend and reactjs in the frontend.
using EasyLink.Server.Database.DbModels;
using EasyLink.Server.Database.DbModels.User;
using EasyLink.Server.Identity;
using EasyLink.Server.Models.Categories.Stock;
using EasyLink.Server.Validations.CamelCaseConcat;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
namespace EasyLink.Server.Services.Stock
{
public class StockService : IStockService
{
private readonly UserManager<ApplicationUser> _userManager;
public StockService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<bool> StockAddData(StockDataRequest request, ClaimsPrincipal User)
{
try
{
var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
if (userIdClaim == null)
{
Console.WriteLine("User ID claim not found.");
return false;
}
var userId = userIdClaim.Value;
var currentUser = await _userManager.FindByNameAsync(userId);
if (currentUser!.Stock == null)
{
Console.WriteLine("Stock is null. Initializing stock.");
currentUser.Stock = new StockModel
{
ApplicationUserId = currentUser.Id,
AutoParts = new List<AutoPart>()
};
}
string fieldName = CamelCase.ConvertToCamelCase(request.Field!);
if (request.Field == "Anvelope" && request.Data!.Categories!.ContainsKey(fieldName))
{
var tyreDataJson = request.Data.Categories[fieldName]?.ToString();
if (string.IsNullOrEmpty(tyreDataJson))
{
Console.WriteLine("Tyre data is null or empty.");
return false;
}
var tyreData = CamelCase.DeserializeJsonCamel<AnvelopeModel>(tyreDataJson);
if (tyreData == null)
{
Console.WriteLine("Failed to deserialize tyre data.");
return false;
}
// Handle potential null values by providing defaults
var newAnvelope = new Anvelope
{
VehicleType = request.Data.Mandatory?.TipVehicul,
PartType = request.Data.Mandatory?.TipPiesa,
Delivery = request.Data.Mandatory?.Nou,
IsNew = request.Data.Mandatory?.Nou,
Price = request.Data.Mandatory?.Pret != null ? Convert.ToInt32(request.Data.Mandatory.Pret) : (int?)null,
Tva = request.Data.Mandatory?.Negociabil,
IsNegotiable = request.Data.Mandatory?.Negociabil,
Stock = currentUser.Stock,
TipDeAnvelope = Enum.TryParse<TyreType>(tyreData.TipDeAnvelope, out var tyreType) ? tyreType : TyreType.ToateSezoanele,
EmisieDeZgomot = tyreData.EmisieDeZgomot,
AderentaPeUmezeala = tyreData.AderentaPeUmezeala,
EficientaInCombustibil = tyreData.EficientaInCombustibil,
LatimeAnvelope = tyreData.LatimeAnvelope,
Producator = tyreData.Producator
};
currentUser.Stock!.AutoParts!.Add(newAnvelope);
}
else
{
Console.WriteLine("Field is not 'Anvelope' or data is missing.");
return false;
}
// Save changes to the database
Console.Write("nnnnnn1111nnnnn");//this writes 1111
var updateResult = await _userManager.UpdateAsync(currentUser);
if (!updateResult.Succeeded)
{
Console.WriteLine($"Failed to update user: {string.Join(", ", updateResult.Errors.Select(e => e.Description))}");
return false;
}
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Exception occurred: {ex.Message} {ex.Source}");
return false;
}
}
}
}
this is from the client-side:
const sendForm = async () => {
const formErrors = [];
const formKeys = Object.keys(formData.mandatory);
formKeys.forEach((e) => {
if (formData.mandatory[e] === "") formErrors.push(e);
});
setError(formErrors);
if (formErrors.length === 0) {
const field = main.partType.data[currentCategoryIndex];
try {
console.log("sent");
const response = await fetch('https://localhost:7128/api/stock/StockAddData', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
Data: formData,
Field: field
})
});
if (response.ok) {
console.log("RIGHT");
} else {
throw new Error('Failed to send data');
}
} catch (error) {
console.error('Error sending data:', error);
}
}
};
I expected the service to return true, but it returns false and the error I mentioned.