Entity Framework SaveChanges does not update db

Using the sql server profiler, I see that the initial request for AnswerComment goes in db, but when I get to ef.SaveChanges (), nothing happens in db. I am using sqlexpress 2008 R2.

using (TPRDEntities ef = new TPRDEntities()) { var ac = ef.AnswerComments.Where(a => a.AnswerCommentID == answercomment.AnswerCommentID).FirstOrDefault(); if (ac == null) { ac = new AnswerComment(); ac.AnswerID = answercomment.AnswerID; ac.DisplayText = answercomment.DisplayText; ac.InsertDate = answercomment.InsertDate; ac.InsertUser = "save test user"; ef.SaveChanges(); } } 
+4
source share
3 answers

New instance you created

 ac = new AnswerComment(); 

not known EF. This is a completely new instance of an object that EF has not previously seen.

You will need to add it to ef.AnswerComments

 ef.AnswerComments.Insert(ac); 

Also, make sure ChangeTracking is active for ef .

+6
source

I think you do not need to add AnswerComment to the context, you should do:

 ac = new AnswerComment(); ac.AnswerID = answercomment.AnswerID; ac.DisplayText = answercomment.DisplayText; ac.InsertDate = answercomment.InsertDate; ac.InsertUser = "save test user"; ef.AnswerComments.Add(ac); ef.SaveChanges(); 
+1
source

You never insert a new element into a table:

 ef.AnswerComments.Insert(ac); ef.SaveChanges(); 
0
source

All Articles