ASP.NET Cored C# Entity - JSON import

asp.net-core asp.net-mvc entity-framework-6 entity-framework-core

Question

I have a JSON string, which looks like this:

I have a JSON string looks like this:

{
    "products":
        {"title1":"description1","title2":"description2","title3":"description3"}, 
    "categories":
        {"1":"cat1","2":"cat2"}
}

My Model class which is similar to the database table:

public class Product
{
    public int Id { get; set; }  //auto generated identity
    public string Title { get; set; }
    public string Description { get; set; }
}


public class ApplicationProduct : DbContext
{
    public ApplicationProduct(DbContextOptions<ApplicationProduct> options) : base(options)
    {

    }
    public DbSet<Product> Product { get; set; }
}

How do I insert the JSON data into the database by using Entity Framework.

[Route("import/products")]
public ActionResult ImportProducts()
{
    string jsonData = ""; //will contain the above mentioned JSON data

    //List<Product> products = JsonConvert.DeserializedObject<List<Product>>(jsonData);
    //foreach(var product in products)
    //{
    //  @product.Title.ToString();
    //  @product.Description.ToString();
    //}
}

I dont know how to achieve this in the controller method ImportProducts. Any help?

1
0
3/21/2020 12:21:27 AM

Popular Answer

This is a non-standard json format, you cannot directly deserialize the obtained content into List.

You need to accept it with a dynamic type first, and then recycle it to get the name and value.

Try this code :

                List<Product> products = new List<Product>();
                string jsonData = "";//your json content
                dynamic DynamicObject = JsonConvert.DeserializeObject<dynamic>(jsonData);
                foreach (var item in DynamicObject.products)
                {
                    Product product = new Product
                    {
                        Description = item.Value,
                        Title = item.Name
                    };
                    _context.Product.Add(product);
                    products.Add(product);
                }
                _context.SaveChanges();
0
3/23/2020 6:10:09 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow