huiru
huiru

Reputation: 69

Foreach tag to loop through c# object and insert to database using Entity Framework

Example of Input Json Format how it looks like:

    {
          Reservations:
          [
              {
                   FacilityReservationID:"....",
                   FacilityID:"....",
                   Description:"...."
              },
                   ........
          ]
    }

Return Result format:

    {
            Result:"OK"/Error",
            Message:"...."
    }

I created a asp.net webform to accept a webservice call from a console app program in Json Restful.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Newtonsoft.Json;
    using System.Data.Entity;

    namespace ReservationListWebService
    {
        public partial class UpdateFacility : System.Web.UI.Page
        {

I created a context to call the EF Database.

            public class KioskContext : DbContext
            {
               //using the FacilityReservationKioskEntities Connection string
               public KioskContext()
                 : base("name=FacilityReservationKioskEntities")
               {
               }
               public DbSet<Department> Departments { get; set; }
               public DbSet<Facility> Facilitys { get; set; }
               public DbSet<FacilityReservation> Reservations { get; set; }
          }


          public class ReservationList
          {
               public string facilityReservationID { get; set; }
               public string facilityID { get; set; }
               public DateTime startDateTime { get; set; }
               public DateTime endDateTime { get; set; }
               public string useShortDescription { get; set; }
               public string useDescription { get; set; }
          }

The console app would call my webform and hence pass me the input of a string. After deserialized into a c# object and i would eventually insert it into the database using Entity framework format. I am not sure what i should input inside the foreach() tag to loop through the c# objects and insert it into the database. I am stuck with the foreach loop.

And also how am i going to return the output result to the console app that pass me the Json data? Please help and guide! thank you!

          protected void Page_Load(object sender, EventArgs e)
          {
               string departmentID = Request.QueryString["DepartmentID"];
               string json = Request.Form["Json"];

               ReservationList list = JsonConvert.DeserializeObject<ReservationList>(json);

               using (var db = new KioskContext())
               {
                     db.Database.ExecuteSqlCommand(
                           "DELETE FacilityReservation FROM Department INNER JOIN Facility ON Department.DepartmentID = Facility.DepartmentID" +
                    "INNER JOIN FacilityReservation ON Facility.FacilityID = FacilityReservation.FacilityID WHERE Department.DepartmentID = '" + departmentID + "'");

                foreach(....)
                {
                     FacilityReservation res = new FacilityReservation();

                     //set all fields here
                     res.FacilityReservationID = list.facilityReservationID;

                     db.Reservations.Add(res);
                }
                db.SaveChanges();
              }
          }
      }
  }

Upvotes: 0

Views: 4004

Answers (2)

Edd
Edd

Reputation: 96

I believe your JSon De-Serialization is not exactly correct. You should de-serialize the JSon array to a list of reservations. Then you can loop through each of the reservation in your foreach loop.

public class FacilityReservation
 {
               public string facilityReservationID { get; set; }
               public string facilityID { get; set; }
               public DateTime startDateTime { get; set; }
               public DateTime endDateTime { get; set; }
               public string useShortDescription { get; set; }
               public string useDescription { get; set; }
}

 public class ReservationList
 {
               public List<FacilityReservation> Reservations {get; set;}
}

....

ReservationList list = JsonConvert.DeserializeObject<ReservationList>(json);

    foreach(FacilityReservation res in list.Reservations)
     {
         FacilityReservation res = new FacilityReservation();

         //set all fields here
         res.FacilityReservationID = list.facilityReservationID;

                  db.Reservations.Add(res);
     }

Upvotes: 1

Kien Chu
Kien Chu

Reputation: 4895

I don't see any problem with your existing code.

You only insert Reservations to database once you call db.SaveChanges(), so it's totally safe when you call db.Reservations.Add(res); inside your foreach

Upvotes: 0

Related Questions