I am building an API using .NET Core and I am trying to insert records into many tables in relationships. I have tables Client
, Shipment
, ShipmentDetail
.
How can I insert records into Client
table then last client id must insert into Shipment
table then shipmentId
(last added one) must insert into shipmentdetails
. And should I do all of these in one controller?
Classes:
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; } = String.Empty;
public string Adress { get; set; }
public List<Shipment> Shipments { get; set; }
}
public class Shipment
{
public int ShipmentId { get; set; }
public DateTime TimeCreated { get; set; }
public string ShippingAddress { get; set; }
public int DeliveryCost { get; set; }
public string OrderNumber { get; set; }
public DateTime EstimatedDate { get; set; }
public int ClientId { get; set; }
public Client Client { get; set; }
public List<ShipmentDetail>? ShipmentDetails { get; set; }
public List<ShipmentStatu>? ShipmentStatus { get; set; }
}
public class ShipmentDetail
{
public int Id { get; set; }
public string DeliveryNumber { get; set; }
public string TrackingNumber { get; set; }
public Shipment Shipment { get; set; }
public int ShipmentId { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
}
What I have tried: I am checking client name and if client exists, I am getting id, else I am inserting a new client and getting new ClientId
:
[HttpPost]
public async Task<ActionResult<List<Shipment>>> AddShipments(ShipmentDto request)
{
var client = _context.Clients.Where(p => p.Name == request.ClientName).Select(p => p.ClientId)
if (client.ToList().Count == 0)
{
var newClient = new Client
{
Name = request.ClientName,
Adress = request.ClientAdress
};
_context.Clients.Add(newClient);
_context.SaveChanges();
var newShipment = new Shipment
{
ClientId = newClient.ClientId,
TimeCreated = Convert.ToDateTime(DateTime.Now.GetDateTimeFormats()[0]),
ShippingAddress = request.ShippingAddress,
DeliveryCost = request.DeliveryCost,
OrderNumber = "x" + DateTime.Now.ToString("MMddyy"),
EstimatedDate = Convert.ToDateTime(DateTime.Now.AddDays(2).GetDateTimeFormats()[0]),
};
_context.Shipments.Add(newShipment);
_context.SaveChanges();
}
else
{
var newShipment = new Shipment
{
ClientId = client.FirstOrDefault(),
TimeCreated = Convert.ToDateTime(DateTime.Now.GetDateTimeFormats()[0]),
ShippingAddress = request.ShippingAddress,
DeliveryCost = request.DeliveryCost,
OrderNumber = "x" + DateTime.Now.ToString("MMddyy"),
EstimatedDate = Convert.ToDateTime(DateTime.Now.AddDays(2).GetDateTimeFormats()[0]),
};
_context.Shipments.Add(newShipment);
_context.SaveChanges();
}
var shipment = _context.Shipments.Max(p => p.ShipmentId);
return Ok(shipment);
}
It works but I don't know what is the best practice for it and should I use many dto or endpoint for nested inserts?