Introduction

This article will help you to insert a record in two tables using Entity Framework Core which has a foreign key relationship.
Step 1 - We will create table in SQL Server
CallDetail Table is Parent table,
  1. CREATE TABLE [dbo].[CallDetail](
  2. [CallID] [int] IDENTITY(1,1) NOT NULL,
  3. [CreatedDate] [datetime] NOT NULL,
  4. [CreatedBy] [uniqueidentifier] NOT NULL,
  5. [FirstName] [nvarchar](50) NOT NULL,
  6. [LastName] [nvarchar](50) NOT NULL,
  7. [MobileNumber] [nvarchar](12) NOT NULL,
  8. [FirmName] [nvarchar](128) NULL,
  9. [Address] [nvarchar](512) NOT NULL,
  10. [LastChangedDate] [datetime] NOT NULL,
  11. [OutComeID] [int] NOT NULL,
  12. [Remark] [nvarchar](max) NULL,
  13. CONSTRAINT [PK_CallDetail] PRIMARY KEY CLUSTERED
  14. (
  15. [CallID] ASC
  16. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  17. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  18. GO
CallTransactionDetail is Child table,
  1. CREATE TABLE [dbo].[CallTransactionDetail](
  2. [CallTransactionID] [int] IDENTITY(1,1) NOT NULL,
  3. [CallID] [int] NOT NULL,
  4. [CreatedDate] [datetime] NOT NULL,
  5. [CreatedBy] [uniqueidentifier] NOT NULL,
  6. [OutComeID] [int] NOT NULL,
  7. [Remarks] [nvarchar](max) NULL,
  8. CONSTRAINT [PK_CallTransactionDetail] PRIMARY KEY CLUSTERED
  9. (
  10. [CallTransactionID] ASC
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  12. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  13. GO
  14. ALTER TABLE [dbo].[CallTransactionDetail] WITH CHECK ADD CONSTRAINT [FK_CallTransactionDetail_CallDetail] FOREIGN KEY([CallID])
  15. REFERENCES [dbo].[CallDetail] ([CallID])
  16. GO
  17. ALTER TABLE [dbo].[CallTransactionDetail] CHECK CONSTRAINT [FK_CallTransactionDetail_CallDetail]
  18. GO
We have assigned a foreign key, CallID, to CallTransactionDetail table which is the primary key in CallDetail table.
Step 2
Create Model Classes using scaffold command in the .net core application in Package Manager Console.
Note
You need to install the nuget package Microsoft.EntityFrameworkCore. For that please execute the below command in Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore -Version 3.1.3
Insert Records In Two Tables In Foreign Key Relationship Using Entity Framework Core
Scaffold-DbContext "Server=.\SQLEXPRESS;Database=dbCallMgt;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
The database is dbCallMgt. It will create the model classes in Models directory in .net core applications.
Insert Records In Two Tables In Foreign Key Relationship Using Entity Framework Core
Step 3
You can see the two classes in Models directory
CallDetail.cs
  1. public partial class CallDetail
  2. {
  3. public CallDetail()
  4. {
  5. CallTransactionDetail = new HashSet<CallTransactionDetail>();
  6. }
  7. public int CallId { get; set; }
  8. public DateTime CreatedDate { get; set; }
  9. public Guid CreatedBy { get; set; }
  10. public string FirstName { get; set; }
  11. public string LastName { get; set; }
  12. public string MobileNumber { get; set; }
  13. public string FirmName { get; set; }
  14. public string Address { get; set; }
  15. public DateTime LastChangedDate { get; set; }
  16. public int OutComeId { get; set; }
  17. public string Remark { get; set; }
  18. public virtual ICollection<CallTransactionDetail> CallTransactionDetail { get; set; }
  19. }
CallTransactionDetail.cs
  1. public partial class CallTransactionDetail
  2. {
  3. public int CallTransactionId { get; set; }
  4. public int CallId { get; set; }
  5. public DateTime CreatedDate { get; set; }
  6. public Guid CreatedBy { get; set; }
  7. public int OutComeId { get; set; }
  8. public string Remarks { get; set; }
  9. public virtual CallDetail Call { get; set; }
  10. }
Step 4
Now we directly go to the Insert method which will insert the record in both tables:
  1. [HttpPost]
  2. public async Task<ActionResult> PostCallDetail(CallDetail callDetail)
  3. {
  4. try
  5. {
  6. if (ModelState.IsValid)
  7. {
  8. callDetail.LastChangedDate = DateTime.Now;
  9. callDetail.CallTransactionDetail.Add(new CallTransactionDetail()
  10. {
  11. CreatedBy = callDetail.CreatedBy,
  12. OutComeId = callDetail.OutComeId,
  13. Remarks = callDetail.Remark,
  14. });
  15. _context.CallDetail.Add(callDetail);
  16. await _context.SaveChangesAsync();
  17. return Ok("Inserted successfully!");
  18. }
  19. else
  20. {
  21. return BadRequest("Failed to insert!");
  22. }
  23. }
  24. catch (Exception ex)
  25. {
  26. return StatusCode(StatusCodes.Status500InternalServerError, ex);
  27. }
  28. }
So, it is very simple to add in both tables by using _context.CallDetail.Add(callDetail); and await _context.SaveChangesAsync(); command of entity framework core.