0
I am using Dotnet Core 3.1 with EF Core. I have three classes in my context:
public class Sale
{
public Sale()
{
this.Cars = new List<Car>();
this.CarSeller = new Seller();
}
[Key]
public int Id { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public ProcessStatusEnum Status { get; set; }
[Required]
public Seller CarSeller { get; set; }
public virtual List<Car> Cars { get; set; }
}
public class Car
{
[Key]
public int Id { get; set; }
[Required]
public string Brand { get; set; }
[Required]
public string Type { get; set; }
[Required]
public int Year { get; set; }
[Required]
public string Fabrication { get; set; }
public Sale Sale { get; set; }
}
public class Seller
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Cpf { get; set; }
[Required]
public string Email { get; set; }
}
My doubt is occurring when I try to insert a new sale:
public ActionResult<int> SaveVehicleSale(SaleDTO newSale)
{
try
{
newSale.Id = 0;
newSale.Status = ProcessStatusEnum.ConfirmingPayment;
if (Functions.IsAnyNullOrEmpty(newSale))
new ApiException(StatusCodeEnum.BadRequest, MsgException.ObjectAtributeNull);
_context.Sale.Add(ConvertType.To(newSale)); //Converte o SaleDTO para o Sale
_context.SaveChanges();
return _apiResponse.ResponseRet<int>(StatusCodeEnum.OK, newSale.Id);
}
catch (ApiException e)
{
return _apiResponse.ResponseRet<int>(e);
}
catch (Exception e)
{
return _apiResponse.ResponseRetWithoutEnumerable(e);
}
}
When entering, it is also trying to add a new Car. How do I make it just reference an existing car? This already happens with the Seller Class, but I don’t know how to do it with a List type<>.
Thank you very much, from now on!
if Car already exists, you can recover so that the EF has track of it: something like this (I’ll make the example as if it were a single object):
newSale.Carro = carroContext.Get(newSale.Carro.Id)
– Ricardo Pontual
I get it. I’ll try that later, thank you!
– Lucas Guille
It worked perfectly, thank you very much!
– Lucas Guille
@Ricardopunctual asked this answer so that we do not leave this question open
– Leandro Angelo