Parent - Child relation Child ID

asp.net-core c# entity-framework-core

Question

I have the following classes

public class Order
{
    public int OrderID {get;set;}
    /*...
    Some other properties
    ...*/
    public ICollection<OrderDetail> Details {get;set;}
}

public class OrderDetail
{
    public int OrderID {get;set;}
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderDetailID {get;set;}
    /*...
    Some other properties
    ...*/

    public Order Order {get;set;}
}

I have also specified the relation in the OnModelCreation like below:

modelBuilder.Entity<OrderDetail>().HasKey(detail => new { detail.OrderID, detail.OrderDetailID});
modelBuilder.Entity<OrderDetail>().HasOne(detail => detail.Order)
                                            .WithMany(order => order.Details)
                                            .HasForeignKey(detail => detail.OrderID).OnDelete(DeleteBehavior.Cascade);

Everything works without any errors.
My problem is that in this case when I create an order with details the OrderDetailID is incremented for all the details and I am getting the below in the database.

OrderID OrderDetailID ....     
17      19              3   15.0000 15.0000 EA      
17      20              3   15.0000 15.0000 EA     
18      21              1   25.0000 0.0000  EA     
18      22              1   25.0000 0.0000  EA     

I understand that the way OrderDetailID works is corresponding to the configuration in my code. But my problem is that I need to get the following picture in the database:

OrderID OrderDetailID ....     
17      1               3   15.0000 15.0000 EA     
17      2               3   15.0000 15.0000 EA     
18      1               1   25.0000 0.0000  EA     
18      2               1   25.0000 0.0000  EA     

In other words I need the OrderDetailID to be reset to 1 for every new order.
I can't find any configuration option in Entity Framework to get this to work in the way that I need.

Thank you in advance.

1
0
1/7/2020 8:46:59 PM

Popular Answer

What you are expecting is called Identity column based on another column. Neither SQL Server nor EF Core has default support for this.

You have to do it manually. In EF Core, you have to assign the property (column) value by getting the max value of this property (column) from database and then incrementing it by 1.

1
1/8/2020 7:19:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow