Json format from angular
books:"tables",
Color:[
Color:red,
Color:white
]
DataModel.cs
public string Books{get;set;}
Public string Colors{get;set;}
How to store in database table like separated by commas in same row of column using C# code
output:Colors
Red,White

Ali BenchaabanRank #925 · 2.2K reputationPosted Sep 16, 2023, 7:23 AM EDT
using System; using System.Collections.Generic; using System.Text.Json; using Microsoft.EntityFrameworkCore; public class BookstoreContext : DbContext { public DbSet DataModels { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Configure the database connection (for example, SQLite) optionsBuilder.UseSqlite("Data Source=yourDB.db"); } } class Program { static void Main() { // Sample JSON data string jsonData = @"{ "Books": "tables", "Color": ["red", "white"] }"; // Deserialize the JSON data into a DataModel object var dataModel = JsonSerializer.Deserialize(jsonData); // Convert the list of colors to a comma-separated string string colorsCsv = string.Join(",", dataModel.Color); // Create a new DataModelContext using (var context = new DBContext()) { // Create a new DataModel object and set its properties var newDataModel = new DataModel { Books = DataModel.Books, Colors = colorsCsv }; // Add the new dataModel to the database context.DataModels.Add(newDataModel); context.SaveChanges(); } } }Prasad RaveendranRank #320 · 7.8K reputationPosted Sep 16, 2023, 8:04 AM EDT
To store data separated by commas in the same row of a database column using C#, you can follow these steps:
Create a model class to represent your data:
public class DataModel { public string Books { get; set; } public string Colors { get; set; } }Deserialize the JSON data from Angular into an instance of the DataModel class:
Concatenate the Color values with commas and store it in the database. Assuming you are using Entity Framework, here's an example of how you can do it:
using (var dbContext = new YourDbContext()) { // Concatenate the Color values with commas string colorsCsv = string.Join(",", data.Colors); // Create a new entity to save in the database var entity = new YourEntity { Books = data.Books, Colors = colorsCsv }; // Add the entity to the DbContext and save changes dbContext.YourEntities.Add(entity); dbContext.SaveChanges(); }In this example, replace YourDbContext with your actual Entity Framework database context class, and YourEntity with the name of the entity you want to save the data in.
This code will deserialize the JSON data, concatenate the Color values with commas, and store them in the Colors column of your database table.