Entity Framework: How to perform the Insert of a table with relation 1.. n without the children also being inserted?

Asked

Viewed 42 times

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!

  • 1

    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)

  • I get it. I’ll try that later, thank you!

  • It worked perfectly, thank you very much!

  • @Ricardopunctual asked this answer so that we do not leave this question open

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.