How to insert master/details data in EF Code First

By FoxLearn 11/9/2024 2:28:14 PM   67
In Entity Framework (EF) Code First, inserting master-detail data involves inserting records into both the "master" and "detail" tables while respecting the relationships between them (such as one-to-many, many-to-one, etc.).

To define a master/details relationship in Entity Framework (EF) Code First, you need to include a reference to the master object in the detail class.

For example, if you have an Order (master) and OrderDetail (detail), you inform EF of the relationship by adding a public Order property in the OrderDetail class. This is the minimum requirement for setting up a master/details relationship. EF will automatically create a foreign key column (Order_Id) in the OrderDetail table and establish the relationship between the two tables.

public class Order
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; } 
    public decimal Total { get; set; }
}
 
public class OrderDetail
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; } 
    public int OrderId { get; set; } 
    [ForeignKey("OrderId")] // if not specifed, Order_Id column will be used
    public Order Order { get; set; } 
    public int ProductId { get; set; }
    public int Qty { get; set; }
}

If you want to use a different column name for the foreign key or if you already have an existing table with a different foreign key column, you can use the `[ForeignKey]` attribute to specify the foreign key column name. Additionally, you need to include the foreign key property in the class definition to properly map the relationship.

How to insert Order/OrderDetails in EF Code First?

public void CreateOrder()
{
    using (var db = new OrderDbContext())
    {
        var order = new Order { Total = 10 };
        db.Orders.Add(order);
        db.OrderDetails.Add(new OrderDetail
        {
            Order = order,
            ProductId = 101,
            Qty = 7
        });
        db.SaveChanges();
    }
}

To add a new `OrderId` to the `OrderDetail` table, simply set the `Order` object reference to the `OrderDetail.Order` property. When the `.SaveChanges()` method is called, EF will automatically set the new `OrderId` in both the `Order` and `OrderDetail` tables.