C# Entity Framework Basics CRUD Operations Updating an Entity

Not sure I understand what's going on here...

The coding challenge says it won't compile... After reviewing the video and other similar questions... I don't get what I'm doing wrong here...

The prompt is: In Repository.cs update the UpdateCourse method to persist changes to a course to the database.

Instantiate an instance of the Context class within a using statement Call the Attach method on the context's Courses DbSet property to attach the course parameter to the context Retrieve the course's entry using the context's Entry method and set its state to "Modified" Call the context's SaveChanges method to persist the changes to the database

public static void UpdateCourse(Course course)
        {
            using (Context context = new Context())
            {
                context.Courses.Attach(course);
                context.Entry(course).State = EntityState.Modified;
                context.SaveChanges();
            }
        }

1 Answer

Steven Parker
Steven Parker
171,120 Points

Apparently (based on the error message) instantiating a "new Context()" creates a ContextProxy object. I admit I'm a bit baffled by that myself. But if you substitute that for the type of "context" you'll pass. An even easier solution is to just use "var" and let the compiler determine the type:

            using (var context = new Context())

Perhaps James Churchill might help us understand the Context vs. ContextProxy thing.