How to insert master/details data in EF Code First
By FoxLearn 11/9/2024 2:28:14 PM 34
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.
- How to use Identity column in EF7
- How to enable MultipleActiveResultSets
- Connection String in Entity Framework 6
- How to use stored procedure in Entity Framework Core
- How to use decimal precision and scale in EF Code First
- How to enable webRTC in CefSharp in C#
- How to fix 'CEF can only be initialized once per process'
- How to prevent target blank links from opening in a new window in Cefsharp