Solved

Storing my json object in the database using entity framework

Posted on 2013-01-25
13
1,405 Views
Last Modified: 2013-01-29
On an earlier post someone answered my question regarding pushing json to a wcf service call and a big thank you for that.

Here is what the code in question

var patient_records = [
    {
        "dob": "3/24/2012 12:00:00 AM",
        "first_name": "FirstName-8604     ",
        "id": 69,
        "last_name": "LastName-8604     ",
        "mrn": "0",
        "pat_seqno": 2121,
        "site_id": 12
    },
    {
        "dob": "1/6/2012 12:00:00 AM",
        "first_name": "FirstName-4     ",
        "id": 70,
        "last_name": "LastName-4     ",
        "mrn": "0",
        "pat_seqno": 2121,
        "site_id": 12
    },
    {
        "dob": "9/8/2012 12:00:00 AM",
        "first_name": "FirstName-840     ",
        "id": 71,
        "last_name": "LastName-840     ",
        "mrn": "0",
        "pat_seqno": 2123,
        "site_id": 12
    }];

    $.ajax({
        type: "POST",
        url: "http://sidwservices/rest/careplan.svc/PutPatientData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify({ patrecs: patient_records }),
        success: function (msg) {
            alert("success : " + msg.d);
        },
        error: function (msg) {
            alert("failed :  " + msg.d);

        }
    });

Open in new window


Now in my back end I am able to traverse through this list in class array called PatientRecords and would like to store the contents in the database.

I am using entity framework, and have that all set up, but not exactly sure how to go about using EF to do what I want (newbie).

I am looking at the following example:

http://www.entityframeworktutorial.net/update-one-to-one-entities-in-entity-framework.aspx#.UQLK5SdEGAo

and the way I am reading this, is that you query the entity first and then apply the values to the fields and save the changes. This seems odd to do this, querying to find it and then applying the changes. Is there a way to do an update, without this approach, or is this the only way to do it?
0
Comment
Question by:JDEE8297
  • 7
  • 3
  • 3
13 Comments
 
LVL 4

Assisted Solution

by:Srinivasulu Muppala
Srinivasulu Muppala earned 175 total points
ID: 38820467
if you implemented Entity framework in webservice you need json data mapping manager class or json serialization, to map data to Entity.

i think your data is not mapped to Entities. let me know what type of webservice you are using.
0
 
LVL 4

Expert Comment

by:Srinivasulu Muppala
ID: 38820479
use RESTfull service approch that help you to simplify your transaction if you realy need json data transfer
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38820752
>Is there a way to do an update, without this approach, or is this the only way to do it?

I think in all Object Relational Mapping frameworks, an object has to be retrieved, updated (property values changed) and then saved.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:JDEE8297
ID: 38821213
I am using restful wcf services, and all of that seems to be working correctly for me,  I did eventually get most of this to work, but when I try to update some fields that are part of the primary key on my table, it throws an error on me. As in it can't update this field because it is part of the primary key on the table.
0
 
LVL 4

Expert Comment

by:Srinivasulu Muppala
ID: 38822027
you have to take care of the data issues such as duplication, parent and child data relation, etc.
0
 

Author Comment

by:JDEE8297
ID: 38826076
sorry....but your last statement is confusing, if I do this in a stored procedure I wouldn't run into this problem. My whole reason for doing this in EF, is not just because it is something else to learn, it is because it is suppose to make life easier when it comes to deployment.

Right now I am the very early stage of this process, and very new to it, so I am not sure where when you say take care of data issues such as duplication, parent and child relations etc. When all I am doing is updating the patient record with data that I know is not already in the database.
0
 

Author Comment

by:JDEE8297
ID: 38826623
The property 'first_name' is part of the object's key information and cannot be modified.

above is the message I am getting when I tried to set the field value in the code below.

public bool SavePatient(sidwservices.rest.PatientRecords[] patr)
        {
            bool blnReturn = false;

            plan_devEntities cp = new plan_devEntities();
            int c = patr.Count();

            for (int i = 0; i < patr.Count(); i++)
            {
                long lngPatRecId = patr[i].id;
                patient pats = (from s in cp.patients
                           where s.id == lngPatRecId
                           select s).FirstOrDefault<patient>();

                //pats.pat_seqno = Convert.ToInt64(patr[i].pat_seqno);
                pats.first_name = patr[i].first_name; //FAILS RIGHT HERE
                pats.last_name = patr[i].last_name;


                cp.SaveChanges();
                
                
            }

                return blnReturn;
        }

Open in new window

0
 

Author Comment

by:JDEE8297
ID: 38827237
I have gotten a wee bit further in this, and I am sure I am breaking all kind of rules, but I am very close to calling this quits on EF for this project.

I changed my c# code and now end up with the following message.

Unable to update the EntitySet 'patient' because it has a DefiningQuery and no <UpdateFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

public bool SavePatient(sidwservices.rest.PatientRecords[] patr)
        {
            bool blnReturn = false;

           plan_devEntities cp = new plan_devEntities();
            
            int c = patr.Count();

            for (int i = 0; i < patr.Count(); i++)
            {

                long lngPatRecId = patr[i].id;

                patient patupdate = new patient();
                patupdate = cp.patients.First(f => f.id == lngPatRecId);
                


                patupdate.first_name = patr[i].first_name;
                patupdate.last_name = patr[i].last_name;
                patupdate.pat_seqno = Convert.ToInt32(patr[i].pat_seqno);
                patupdate.mrn = patr[i].mrn;
                patupdate.site_id = patr[i].site_id;

                //cp.AddObject(patupdate);



                

                //patient pats = (from s in cp.patients
                //           where s.id == lngPatRecId
                //           select s).FirstOrDefault<patient>();
                
                


                ////pats.pat_seqno = Convert.ToInt64(patr[i].pat_seqno);

                //pats.first_name = patr[i].first_name;
                //pats.last_name = patr[i].last_name;
                

                cp.SaveChanges(); //Now fails here with the above error message
                
                
            }

                return blnReturn;
        }

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38827372
I think included fields like first_name will create problems for you as evident here. If you are going with EF, you would probably need to use a single Identity type column as primary key.
0
 

Author Comment

by:JDEE8297
ID: 38827407
@CodeCruiser is that something I changed in EF or on the table itself, if on the latter then I am not sure what the benefit is of EF going forward.

Sorry for all the silly questions on this, but at the end of the day, I just want to build something that will work and not having to jump through hoops to make it work.
0
 

Author Comment

by:JDEE8297
ID: 38828092
in my database I have a primary key, but it is not the id field on the table, it split across the following

site_id, pat_Seqno, mrn, first_name and last_name.

If I set this up in the database and readd it back to the ef, then I get the original error that I was getting which is where I can't update the first_name and so on. However, without the primary key then I get the defining error message.

Feels like a catch 22 situation, bolloxed if I dont have it and bolloxed if I do have it.
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 175 total points
ID: 38830583
Learning curve with frameworks like EF and NHibernate is very steep so if you need to get this project done, I think you are in right track thinking of going without EF. LINQ2SQL may be an easier option.
0
 

Author Closing Comment

by:JDEE8297
ID: 38831076
Thank ye for yer help on this, at the end of the day, it is all about getting the project done and as much I have enjoyed learning more about EF. I still think there is a lot of things that I don't know about it.<br /><br />And I know to some this may be old fashion, but you know what, stored procedures have always worked and have always done a very nice job for me. I can build out this backend with EF in mind, that at a later date, it can be plugged back in on the backend and not affect the front end in any shape or form. Which again is the cool feature of .NET, so thanks again for yer help on this.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question