6

I am working on an asp.net mvc 5 with EF 6. and is there any differences between writing the following code , when Adding new object:-

db.Students.Add(student);
db.SaveChanges();

OR

db.Entry(student).State = EntityState.Added;
db.SaveChanges();

and similarly when Deleting object:-

db.Entry(studentToDelete).State = EntityState.Deleted;
db.SaveChanges();

OR

db.Remove(StudentToDelete)
db.SaveChanges();

Thanks

John John
  • 1
  • 72
  • 238
  • 501
  • possible duplicate of [What is the difference between IDbSet.Add and DbEntityEntry.State = EntityState.Added?](http://stackoverflow.com/questions/9082922/what-is-the-difference-between-idbset-add-and-dbentityentry-state-entitystate) – Colin Oct 28 '14 at 16:45
  • @Colin but the two answers in your link are not exactly the same, as one of the replies mentioned that using the two approaches will have the same effect. while the other reply mentioned that when using .Add & .Remove the related navigation properties for the entity will be added or deleted,, so i am not sure which answer is correct? – John John Oct 28 '14 at 23:18
  • Good point. I hadn't spotted that, but I think the second answer is the correct one. I will post a comment on the accepted answer asking for clarification. Meanwhile, I recommend that you read this article: http://msdn.microsoft.com/en-us/magazine/dn166926.aspx You can avoid most issues with the Add method and disconnected entities by working with foreign keys. – Colin Oct 29 '14 at 14:45
  • @Colin it is good that you have noted this ,, but did you also suggest closing this question,, as there is 3 requests to close this question,, although i find that it is still considered a new and valid question.. – John John Oct 29 '14 at 16:09
  • Ladislav Mrnka has now corrected the answer to the question I linked to so you have a definitive answer for the Add bit of your question. Removed my vote because the Delete remains unanswered - but maybe you could improve your question title? – Colin Oct 29 '14 at 16:26
  • @Colin his answer is regarding .Add , but i am not sure how the Deleted & Changed reacts? – John John Oct 31 '14 at 16:54

0 Answers0