Save data from an array to a database

Asked

Viewed 700 times

1

I need to record the contents of an array that returned from a Json deserilization (return of 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; }
    }

I thank from the outset those who can help.

  • What approach are you using? Entityframework?

  • Rodrigo, I’m using Framework 4.5.2.

  • Rodrigo’s question is if you are using any ORM, like Entityframework, Dapper or if you are using ADO.NET in your project.

  • only one detail, Departments and Departmants ;)

1 answer

0

You have some options, use Entityframework, Dapper, ADO Net or any other. I will put here two examples of Insert using your object. Now just adapt to your columns and table template and realize the Insert, Update or Delete. I particularly like working with the 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 to Nuget on 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.