These are my entities:
public class Order
{
[Key]
public long OrderId { get; set; }
public string CustomerId { get; set; }
[ForeignKey("CustomerID")]
[Required]
public Customer Customer { get; set; }
public long EmployeeId { get; set; }
[ForeignKey("EmployeeID")]
public Employee Employee { get; set; }
...
public ICollection<OrderDetail> OrderDetails { get; set; }
}
public class OrderDetail
{
// public long Id { get; set; }
[Key, Column(Order = 0)]
public long OrderId { get; set; }
[ForeignKey("OrderID")]
public Order Order { get; set; }
public long ProductId { get; set; }
public Product Product { get; set; }
public double UnitPrice { get; set; }
public long Quantity { get; set; }
public double Discount { get; set; }
}
public class Category
{
[Key]
public long CategoryId { get; set; }
public string CategoryName { get; set; }
}
I need to implement AddOrderAsync
and UpdateOrderAsync
methods. I have tried a lot of variants but getting different types of errors like
System.InvalidOperationException : The instance of entity type ‘Category’ cannot be tracked because another instance with the same key value for {‘CategoryId’} is already being tracked.
public async Task<long> AddOrderAsync(RepositoryOrder order)
{
var entityOrder = order.ToEntityOrder();
this.context.Orders.Add(entityOrder);
// Add the order details
foreach (var detail in order.OrderDetails)
{
this.context.OrderDetails.Add(detail.ToEntityOrderDetail());
}
// Save changes
await this.context.SaveChangesAsync();
// Commit transaction
await transaction.CommitAsync();
return entityOrder.OrderId;
}
New contributor
Hamidulla Orifov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.