locked
JSON object, array and LinqtoSQL RRS feed

  • Question

  • I am getting a string object back once the user does an insert. The valid JSON string looks like this

    {
      "FirstNameInfo": "F",
      "LastNameInfo": "sf",
      "CategoriesSelected": [
        "3",
        "4"
      ]
    }

    I want to be able to do an insert in the UserCatagories table using linq to SQL for the  CategoriesSelected variable. But I am not sure how to insert values "3" and "4" in the table. I am stuck in the following code where the line is commented, now sure how to specify clearly how to pick values.

    [System.Web.Services.WebMethod]
            public static void CreateUser(string sUserInfo)
            {        
                JObject jobj = JObject.Parse(sUserInfo);
                UsersDataContext db = new UsersDataContext();
                User newUser = new User
                {
                    FirstName =  (string)jobj["FirstNameInfo"],
                    LastName =  (string)jobj["LastNameInfo"]            
                };
                db.Users.InsertOnSubmit(newUser);
    
                var ocat = from cat in  jobj["CategoriesSelected"].ToArray()
                           select new UserCategory {
                                UserKey = newUser.UserId,
                             // CategoryKey =cat.Value()   // STUCK HERE
                };
                
                db.SubmitChanges();
                  }

    Thanks for the help!

    -Sarah

    Tuesday, February 26, 2013 12:58 AM

Answers

  • Hi again, Sarah.

    What you need to do is add a list of categories to your new User object in order to insert the user and their categories all together.

    You could perfrom this with using a foreach statement. Something like this:

    JArray categories = (JArray)jobj["CategoriesSelected"];
    foreach(var cat in categories) {
         var userCat = new UserCategory
                           {
                               UserKey = newUser.UserId,
                               CategoryKey = Convert.ToInt32(cat)
                           };
         newUser.Categories.Add(userCat));
    }
    db.Users.InsertOnSubmit(newUser);
    db.SubmitChanges();

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.


    • Edited by JA Reyes Thursday, February 28, 2013 9:22 AM Syntax
    • Marked as answer by Sarah2005 Thursday, March 7, 2013 6:00 PM
    Thursday, February 28, 2013 9:21 AM
  • Hi again, Sarah.

    The "=>" notation is a lambda operator, and it is used in Linq query syntax language:

    http://msdn.microsoft.com/en-us/library/bb397947.aspx

    See this other link to see how lambda expressions are build in C#:

    http://msdn.microsoft.com/en-us/library/bb397687.aspx

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    • Marked as answer by Sarah2005 Thursday, March 21, 2013 8:16 PM
    Friday, March 8, 2013 8:56 AM

All replies

  • Anyone? Please need help soon on this..

    Thanks

    -Sarah

    Tuesday, February 26, 2013 6:34 AM
  • Hi @Sarah,

    Take a look at this other thread:

    How to Convert JSON object to Custom C# object?

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    Tuesday, February 26, 2013 1:29 PM
  • Hi again,

    Anyway, something like this should work:

                JArray categories= (JArray)jobj["CategoriesSelected"];
    
                var ocat = from cat in categories
                           select new UserCategory {
                                UserKey = newUser.UserId,
                                CategoryKey = Convert.ToInt32(cat.Key)
                };
    

    Regards.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    Tuesday, February 26, 2013 2:31 PM
  • Thanks muc JA Reyes for your help on this.

    The "Key" field you mentioned is erroring out. "CategoriesSelected": [
        "3",
        "4"]

    When there is no name for the object in the array, I am not sure how to grab it, as "value", or "key" arent showing up. So I just did Convert.toInt32(cat)

    So this goes but it only adds entry in the user table and not in the categories table. I am not sure where to put the insert statement in LInq for categories table

    [System.Web.Services.WebMethod]
            public static void CreateUser(string sUserInfo)
            {
             
                JObject jobj = JObject.Parse(sUserInfo);
               JArray jar = (JArray)jobj["CategoriesSelected"];
    
                UsersDataContext db = new UsersDataContext();
                User newUser = new User
                {
                   FirstName =  (string)jobj["FirstNameInfo"],
                    LastName =  (string)jobj["LastNameInfo"], 
                    Department = (string)jobj["DepartmentInfo"],
                    LoginMachineName =(string)jobj["LoginMachineNameInfo"],   
                   
                };
    
    
                JArray categories = (JArray)jobj["CategoriesSelected"];
    
                var ocat = from cat in categories
                           select new UserCategory
                           {
                               UserKey = newUser.UserId,
                               CategoryKey = Convert.ToInt32(cat)
                           };
      db.Users.InsertOnSubmit(newUser);
                          db.SubmitChanges();
                       }

    Thanks for your help on this.

    -Sarah

    Tuesday, February 26, 2013 5:28 PM
  • Hi @Sarah,

    I think you just need to add each new UserCategory to the new User object. So you should perform something like this:

    [System.Web.Services.WebMethod]
            public static void CreateUser(string sUserInfo)
            {
             
                JObject jobj = JObject.Parse(sUserInfo);
               JArray jar = (JArray)jobj["CategoriesSelected"];
                UsersDataContext db = new UsersDataContext();
                User newUser = new User
                {
                   FirstName =  (string)jobj["FirstNameInfo"],
                    LastName =  (string)jobj["LastNameInfo"], 
                    Department = (string)jobj["DepartmentInfo"],
                    LoginMachineName =(string)jobj["LoginMachineNameInfo"],   
                   
                };
                JArray categories = (JArray)jobj["CategoriesSelected"];
                var ocat = from cat in categories
                           select new UserCategory
                           {
                               UserKey = newUser.UserId,
                               CategoryKey = Convert.ToInt32(cat)
                           };
      categories.Foreach(cat => newUser.Categories.Add(cat));
      db.Users.InsertOnSubmit(newUser);
                          db.SubmitChanges();
                       }

    Hope this can help you.

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    Wednesday, February 27, 2013 10:31 AM
  • Thanks so much for helping m eout here.

    So its not liking this line and giving an error on foreach

    categories.Foreach(cat => newUser.UserCategories.Add(cat));

    Also what does "=>" does?

    Also i am not sure what exactly are we doing in the following piece of code. Are we creating an anonlmus type ocat object and assigning new objects of UserCategories to this object? So oCat can be a linked list or an array of objects of type usercategory?

     var ocat = from cat in categories
                                   select new UserCategory
                                   {
                                       UserKey = newUser.UserId,
                                       CategoryKey = Convert.ToInt32(cat)
                                   };

    Wednesday, February 27, 2013 8:47 PM
  • Hi again, Sarah.

    What you need to do is add a list of categories to your new User object in order to insert the user and their categories all together.

    You could perfrom this with using a foreach statement. Something like this:

    JArray categories = (JArray)jobj["CategoriesSelected"];
    foreach(var cat in categories) {
         var userCat = new UserCategory
                           {
                               UserKey = newUser.UserId,
                               CategoryKey = Convert.ToInt32(cat)
                           };
         newUser.Categories.Add(userCat));
    }
    db.Users.InsertOnSubmit(newUser);
    db.SubmitChanges();

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.


    • Edited by JA Reyes Thursday, February 28, 2013 9:22 AM Syntax
    • Marked as answer by Sarah2005 Thursday, March 7, 2013 6:00 PM
    Thursday, February 28, 2013 9:21 AM
  • Thanks much JA Reyes, that helped alot.

    I still would wamt to understand what does  "=>" notation mean in LINQ Queries?

    Thanks

    -Sarah

    Thursday, March 7, 2013 5:59 PM
  • Hi again, Sarah.

    The "=>" notation is a lambda operator, and it is used in Linq query syntax language:

    http://msdn.microsoft.com/en-us/library/bb397947.aspx

    See this other link to see how lambda expressions are build in C#:

    http://msdn.microsoft.com/en-us/library/bb397687.aspx

    Regards,

    JA Reyes.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    • Marked as answer by Sarah2005 Thursday, March 21, 2013 8:16 PM
    Friday, March 8, 2013 8:56 AM
  • Thanks very much Ja reyes for your help.. I got all that solved. Thanks

    -Sarah

    Thursday, March 21, 2013 8:17 PM