Base solution for your next web application
Open Closed

Many to many relationship - best practice #4099


User avatar
0
affern created

Hello.

I have a problem with duplicate values get inserted in sub entities when I update main entity because I don't use composite keys. Let say you have an Order class with many-to-many relationship to OrderItems:

public class Order : FullAuditedEntity<long> { public virtual ICollection<OrderItem> OrderItems { get; set; } }

How do I design the OrderItem class?

When I do this: public class OptionItem : FullAuditedEntity<long> {
public long OrderId { get; set; }
public string ItemText { get; set; } public int ItemValue { get; set; } }

then Entity Framework insert the same OptionItems in db everytime Order is updated. I wonder what is best practice in Asp.Net Zero framework to manage this? Shoud I use composite keys in the OptionItem class or should I handle this in a different way? I think it would be easy to have composite keys because then I can delete all items with OrderId before I update Order again. But I can't figure out how I implement this in Asp.Net Zero.


5 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    What you have described is a many-to-one relationship. Can you show relevant code that you use to update an Order?

  • User Avatar
    0
    affern created

    public async Task UpdateOrder(OrderInput input) { if (input.Id > 0) {
    input.Status = OrderHelper.SetOrderStatus(input); var order = ObjectMapper.Map<Order>(input); order.CreatorUserId = AbpSession.UserId.Value; await _orderRepository.UpdateAsync(order); } }

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Can you also share your OrderInput class ?

    Thanks.

  • User Avatar
    0
    affern created

    I have solved my problem. The Id is not set on the client side. So I solved this by deleting order items in the database before I save and insert it again. Maybe not an ideal solution but it works. But I'm wondering is whether you have an example of how to use a combined key in an entity class and how this is handled in the service.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @affern,

    I'm not sure if your case is related to combined key but it should not be different in AspNet Zero than any other Entity Framework project. You can check Entity Framework samples on the web.

    We can help you in case you have a problem.

    Thanks.