how to show web api data in my sql

RAVI 1,076 Reputation points
2025-03-27T11:27:19.29+00:00

Hello

We Have One Webapi running fine when we enter this url localhost/testapp/api/values/getdata

now we need to insert this data automtically in my sql table how to do so please guide step by step
{

"Table": [

{

  "Stduent_Join_Date": "12-MAR-2024",

  "Student_No": "LC/1820/24-25",

  "Student_Name": "MI"

},

{

  "Stduent_Join_Date": "18-MAR-2024",

  "Student_No": "LC/1821/24-25",

  "Student_Name": "LK"



}

]

}

Developer technologies | ASP.NET | ASP.NET API
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,236 Reputation points Volunteer Moderator
    2025-03-27T16:06:52.6033333+00:00

    using the dapper sql library:

    // call webapi
    var students = GetApiData();  
    
    // insert in table
    var sql = "insert MyTable (Stduent_Join_Date,Student_No,Student_Name) values(@Stduent_Join_Date,@Student_No,@Student_Name)";
    using (var connection = new SqlConnection(connString))
    {
        connection.Open();
        foreach(var student in students)
        {
            connection.Execute(sql, student);
        }
    }
    
    0 comments No comments

  2. SurferOnWww 4,721 Reputation points
    2025-03-28T00:53:26.2666667+00:00

    now we need to insert this data automtically in my sql table how to do so please guide step by step

    (1) Try using EF Core.

    (2) Create context class and entity class form your database. See Scaffolding (Reverse Engineering) for details.

    (3) Create controller and action method. It will be automatically done using scaffolding operation available in Visual Studio.

    (4) Modify the created action method if required to accept your data.

    0 comments No comments

  3. Danny Nguyen (WICLOUD CORPORATION) 410 Reputation points Microsoft External Staff
    2025-07-11T07:56:13.3066667+00:00

    Hi, to insert the provided JSON data into a table in your ASP.NET Core application, you'll generally follow these steps: 

    1. Define Your Model Class

    First, create C# classes that represent the structure of your JSON data. This allows you to deserialize the JSON into objects that your application can work with.

    public class Student{
        public DateTime Student_Join_Date { get; set; }
        public string Student_No { get; set; }
        public string Student_Name { get; set; }
    }
    public class RootObject{
        public List<Student> Table { get; set; }
    }
     
    
    

     2. Choose Your Data Access Method

    You have several options for interacting with your database in ASP.NET Core. The most common are Entity Framework Core (EF Core) and Dapper.


    Option A: Using Entity Framework Core

    a. Configure DbContext

    If you haven't already, set up your DbContext to represent your database and table.

    // Data/ApplicationDbContext.cs
    public class ApplicationDbContext : DbContext{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)    
    	{
    	}
    	public DbSet<Student> Students{ get; set; }
    }  
    

    b. Add a Migration (if needed)

    If you're creating the table for the first time or modifying its schema, create and apply a migration:

    dotnet ef migrations add AddStudentsTable
    dotnet ef database update
    

    c. Deserialize and Insert Data

    In your controller or service, you would:

    using Newtonsoft.Json; // or System.Text.Jsonpublic 
    class YourController : ControllerBase{
        private readonly ApplicationDbContext _context;
        public YourController(ApplicationDbContext context)    
    	{
    	_context = context;    
    	}
    	
        [HttpPost("insertStudents")]
        public async Task<IActionResult> InsertStudents([FromBody] RootObject data)    
    	{        
    		if (data?.Table == null || !data.Table.Any())
            {            
    			return BadRequest("No student data provided.");
            }
            foreach (var student in data.Table)
            {
                // You might need to parse the date string if it's not directly deserializing// For example, if "12-MAR-2024" doesn't automatically convert to DateTime// student.Student_Join_Date = DateTime.ParseExact(student.Student_Join_DateString, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
                _context.Students.Add(student);
            }
            await _context.SaveChangesAsync();
            return Ok("Students inserted successfully.");
        }
    }
    

    Note on Date Parsing: The date format "DD-MON-YYYY" (e.g., "12-MAR-2024") might not automatically deserialize into a DateTime object using default JSON deserializers. You might need a custom JsonConverter or parse it manually after deserialization. If using System.Text.Json, you can use [JsonConverter(typeof(JsonStringEnumConverter))] for enums or custom converters for dates. With Newtonsoft.Json, you can use DateFormatString attribute or custom converters. For simplicity in the example, I've assumed direct deserialization might work if your setup handles it, otherwise, you'd add parsing logic.


    Option B: Using Dapper

    Dapper is a micro-ORM that provides a lightweight way to execute raw SQL queries. This is good if you need more control over SQL or have performance-critical operations where EF Core might introduce overhead.

    a. Install Dapper

    dotnet add package Dapper
    dotnet add package System.Data.SqlClient // If using SQL Server
    

    b. Deserialize and Insert Data

    using Dapper;
    using System.Data.SqlClient; // Or other appropriate ADO.NET provider
     
    public class YourController : ControllerBase
    {
        private readonly IConfiguration _configuration;
     
        public YourController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
     
        [HttpPost("insertStudentsDapper")]
        public async Task<IActionResult> InsertStudentsDapper([FromBody] RootObject data)
        {
            if (data?.Table == null || !data.Table.Any())
            {
                return BadRequest("No student data provided.");
            }
     
            string connectionString = _configuration.GetConnectionString("DefaultConnection");
            string sql = @"INSERT INTO Students (Student_Join_Date, Student_No, Student_Name)
                           VALUES (@Student_Join_Date, @Student_No, @Student_Name)";
     
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                foreach (var student in data.Table)
                {
                    // Again, handle date parsing if necessary
                    // DateTime parsedDate = DateTime.ParseExact(student.Student_Join_DateString, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
     
                    await connection.ExecuteAsync(sql, new { student.Student_Join_Date, student.Student_No, student.Student_Name });
                }
            }
     
            return Ok("Students inserted successfully using Dapper.");
        }
    }
     
    

    3. Register Services in Program.cs

    If using EF Core, register your DbContext:

    // Program.cs
    using Microsoft.EntityFrameworkCore;
    // ... other usings
     
    var builder = WebApplication.CreateBuilder(args);
     
    // Add services to the container.
    builder.Services.AddControllers();
     
    // Configure EF Core
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
     
    var app = builder.Build();
     
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
     
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    

    To test this, go to the url that triggers your controller action, and check if the data is being added to the database.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.