Save data from an array to a database

1

I need to write the contents of an array that returned from a Json deserialization (return from a Json with more than one level), follow the line with the method that extracts the array:

        Departmants dept = new Departmants();
        dept.Property1 = JsonConvert.DeserializeObject<Department[]>(json);

Class with array structure:

   public class Departmants
    {
        public Department[] Property1 { get; set; }
    }

    public class Department
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool temSub{ get; set; }
        public Sub[] subitem{ get; set; }
    }

    public class Sub
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool temSub{ get; set; }
        public object[] subitem{ get; set; }
    }

Thank you in advance for those who can help.

    
asked by anonymous 21.12.2017 / 19:55

1 answer

0

You have some options, use EntityFramework , Dapper , ADO.Net or any other. I'll put here two examples of insert using its object. Now just adapt to your columns and table template and do the Insert , Update or Delete . I particularly like working with Dapper .

With ADO:

using(SqlConnection connection = new SqlConnection("connectionstring")
{
    connection.Open();
    string sql =  "INSERT INTO Departmants (coluna1 ,coluna1) VALUES(@param1, @param2)";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.Parameters.Add("@param1", SqlDbType.Varchar, 50).value = Departmants.name;  
        cmd.Parameters.Add("@param2", SqlDbType.Bool).value = Departmants.temsub;
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
}

With Dapper: Add the package in Nuget in the Package Manager Console

  

Install-Package Dapper

using (var db = new SqlConnection(connstring))
{
    const string sql = @"INSERT INTO Departmants (coluna1 ,coluna1) VALUES(@param1, @param2)";

    db.Execute(sql, new { param1 = Departmants.name, param2 = Departmants.temsub }, commandType: CommandType.Text);
}
    
28.12.2017 / 10:59