Solved

Storing my json object in the database using entity framework

Posted on 2013-01-25
13
1,340 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
Comment Utility
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
Comment Utility
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
Comment Utility
>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
 

Author Comment

by:JDEE8297
Comment Utility
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
Comment Utility
you have to take care of the data issues such as duplication, parent and child data relation, etc.
0
 

Author Comment

by:JDEE8297
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:JDEE8297
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
@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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

728 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now