Adding Data to a very nested child object using EntityFramework

I am trying to add a note to my event object. I am getting an error using this code

  Note noteToAdd = new Note { State = State.Added, NoteText = note };
  Patient patient = context.Patients.Find(patientId);
  patient.State = State.Modified;
  patient.MobilePatient.State = State.Modified;
  patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid).Note = noteToAdd;
  context.ApplyStateChanges();

Is there a better way to do it using Linq To Entity?

The error that I am having is :

{"Invalid column name 'Note_Id'."}

and the SQl that is being generated is a SELECT instead of INSERT.

Thank you

Answers


but your map shows a one-to-many relation between Note and Event...

all of your code remain as they are, but instead of this line :

patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid).Note = noteToAdd;

replace these lines:

noteToAdd.EventID = oEvent.ID; // replace field names, to exactly what they are; 
context.Note.Add(noteToAdd);
var oEvent = patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid);
oEvent.NoteID = noteToAdd.ID; // replace field names, to exactly what they are;    

also i think if you don`t write these two:

var oEvent = patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid);
oEvent.NoteID = noteToAdd.ID; // replace field names, to exactly what they are;

there is not any problem, i`m not sure


According to your map, Event entity has a list of Note as navigation property, and i think you should add to this collection instead, what you write in this line:

patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid).Note = noteToAdd;

i think should be like this:

patient.MobilePatient.MCalmEvents.Find(e => e.Id == eventid).Add(noteToAdd);

in addition, what kind of error you get ? can you explain your error ?


are sure there is no add method on Event navigation property why don`t you try to add note from context directly? like:

context.Note.Add(noteToAdd);

Need Your Help

SubWebFolder and mutliple bin folders with Website model?

asp.net web projects

I am looking for some advice on how what is the best approach to subweb folders and having mutliple bin folders in the WebSite Project model. For adding new pages at a later stage without recompili...