Answered by:
Update Detached entity in EF 6

Question
-
I'm new to Entity Framework and I'm using Mock to test my repository. The repository uses a class that implements DbContext.
When I run the update test on a tracked entity, it works fine but when I do it on a detached one, it doesn't update the entity.
I currently use the method Attach to update it. I even tried other methods below but no success. I need advice on that.
myContext.Set<Blog>().Attach(detachedBlog);
Entry<Blog>(myBlog).State = EntryState.Modified;
Entry<Blog>(existingBlog).CurrentValues.SetValues(detachedBlog);
Thursday, June 4, 2015 9:29 PM
Answers
-
In EF 6 you can just set the state of the entity to modified and then save it.
Blog detachedBlog = new Blog() { Id = 1, Name = "New Blog Again" }; using (var ctx = new BlogDBEntities()) { ctx.Entry(detachedBlog).State = EntityState.Modified; ctx.SaveChanges(); }
Friday, June 5, 2015 1:03 AM
All replies
-
Thursday, June 4, 2015 9:52 PM
-
The question is how do I update the database using a detached entity with Entity Framework 6.
Knowing that my database already has a record ( Id = 1, Name = "New Blog"), how do I use the code below to update it without having to update every property separately?
Blog detachedBlog = new Blog() { Id = 1, Name = "New Blog Again" }; using (var ctx = new BlogDBEntities()) { ctx.Blogs.Attach(detachedBlog); ctx.SaveChanges(); }
Thursday, June 4, 2015 10:15 PM -
In EF 6 you can just set the state of the entity to modified and then save it.
Blog detachedBlog = new Blog() { Id = 1, Name = "New Blog Again" }; using (var ctx = new BlogDBEntities()) { ctx.Entry(detachedBlog).State = EntityState.Modified; ctx.SaveChanges(); }
Friday, June 5, 2015 1:03 AM -
When I run my unit test on it I get a null pointer exception. My unit Test is mocking BlogDBEntities. I'm not sure if that's the reasonTuesday, June 16, 2015 1:16 PM
-
Hello Ken Taps,
>> When I run my unit test on it I get a null pointer exception. My unit Test is mocking BlogDBEntities. I'm not sure if that's the reason
Please try a simple console application to call the BlogDBEntities to check if you would still encounter a null pointer exception.
Regards.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.Wednesday, June 17, 2015 8:00 AM