Insert Records In Two Tables In Foreign Key Relationship Using Entity Framework Core

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] [intNOT NULL,    
  12.        [Remark] [nvarchar](maxNULL,    
  13.     
  14.  CONSTRAINT [PK_CallDetail] PRIMARY KEY CLUSTERED    
  15. (    
  16.        [CallID] ASC    
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  18. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]    
  19. GO    
CallTransactionDetail is Child table,
  1. CREATE TABLE [dbo].[CallTransactionDetail](    
  2.     [CallTransactionID] [int] IDENTITY(1,1) NOT NULL,    
  3.     [CallID] [intNOT NULL,    
  4.     [CreatedDate] [datetime] NOT NULL,    
  5.     [CreatedBy] [uniqueidentifier] NOT NULL,    
  6.     [OutComeID] [intNOT NULL,    
  7.     [Remarks] [nvarchar](maxNULL,    
  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 = ONON [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.     
  18. ALTER TABLE [dbo].[CallTransactionDetail] CHECK CONSTRAINT [FK_CallTransactionDetail_CallDetail]    
  19. 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 { getset; }    
  8.         public DateTime CreatedDate { getset; }    
  9.         public Guid CreatedBy { getset; }    
  10.         public string FirstName { getset; }    
  11.         public string LastName { getset; }    
  12.         public string MobileNumber { getset; }    
  13.         public string FirmName { getset; }    
  14.         public string Address { getset; }    
  15.         public DateTime LastChangedDate { getset; }    
  16.         public int OutComeId { getset; }    
  17.         public string Remark { getset; }    
  18.     
  19.         public virtual ICollection<CallTransactionDetail> CallTransactionDetail { getset; }    
  20.     }    
CallTransactionDetail.cs
  1. public partial class CallTransactionDetail    
  2.     {    
  3.         public int CallTransactionId { getset; }    
  4.         public int CallId { getset; }    
  5.         public DateTime CreatedDate { getset; }    
  6.         public Guid CreatedBy { getset; }    
  7.         public int OutComeId { getset; }    
  8.         public string Remarks { getset; }    
  9.     
  10.         public virtual CallDetail Call { getset; }    
  11.     }   
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.     
  16.                     _context.CallDetail.Add(callDetail);    
  17.                     await _context.SaveChangesAsync();    
  18.                     return Ok("Inserted successfully!");    
  19.                 }    
  20.                 else    
  21.                 {    
  22.                    return BadRequest("Failed to insert!");    
  23.                 }    
  24.             }    
  25.             catch (Exception ex)    
  26.             {    
  27.                 return StatusCode(StatusCodes.Status500InternalServerError, ex);    
  28.             }    
  29.         }    
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.


Similar Articles