The structure of the Context.SaveChanges object does not work at all

I am having problems with this code. I can connect to the mdf example database file and create an entity model. Although I can query the context model and get information from the database when I try to update, delete or insert something into the context and translate the changes into the DB Context. Does not work. There is no exception, the Entity model is updated properly, but the DB has no changes. Thanks that

public void addCourse(int courseId, int deptId, string courseTitle) { SchoolContexto = new SchoolEntities(); Course mycourse= new Course(); mycourse.CourseID = courseId; mycourse.Credits = 10; mycourse.DepartmentID = deptId; mycourse.Title = courseTitle; SchoolContexto.Courses.Add(mycourse); SchoolContexto.SaveChanges(); SchoolContexto.Dispose(); } 
+8
c # entity-framework-5 visual-studio-2012
source share
5 answers

Make the .mdf file property in your solution how to Copy to output directory: "Only copy if new"

Otherwise, your db file will be overwritten every time it starts.

+6
source share

I suggest you use this code:

 public void addCourse(int courseId, int deptId, string courseTitle) { SchoolEntities entities = new SchoolEntities(); Course mycourse= new Course(); mycourse.CourseID = courseId; mycourse.Credits = 10; mycourse.DepartmentID = deptId; mycourse.Title = courseTitle; entities.Courses.Add(mycourse); entities.SaveChanges(); } 

If this does not work, I suggest you check the app.config file :)

+2
source share

Another way to add a new object to the context is to change its state to Added. Have you tried this

 using (var entities = new SchoolEntities()) { Course mycourse= new Course(); mycourse.CourseID = courseId; mycourse.Credits = 10; mycourse.DepartmentID = deptId; mycourse.Title = courseTitle; context.Entry(mycourse).State = EntityState.Added; entities.SaveChanges(); } 
+1
source share

I solved the problem by including the following namespace

 using System.Data.SqlClient; 
0
source share

I think the problem is that you are working with a localdb file (.mdf). I had the same problem, but when I created a new (SQL Server database connection) Server name: (localdb) \ MSSqlLocaldb .... it worked

0
source share

All Articles