Skip to main content
Commonmark migration
Source Link
  1. I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the

    I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique.

    DataGridView. But, their id value is always 0. And, I need for the id
  2. When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.

    value to be unique.
  1. When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.
// this would be global 
private List<student> studentList = new List<student>();

public void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)
{
    var _student = new student 
    {
        Id = id,
        StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),
        StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),
        CurrentCredits = currentCredits,
        TotalCredits = totalCredits
    };
    
    studentList.Add(_student);
}


public void CommitNewStudents()
{
    // get the new students that have not been committed yet.
    var numberOfnewStudents = studentList.Count;
    
    if(numberOfnewStudents > 0)
    {
        //get the current max Id from the database.
        var maxDbId = student.NewId();
        
        for(int x =0; x < numberOfnewStudents; x++)
        {    
            // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. 
            studentList[x].Id = maxDbId + x;
        }
        
        //now, add them to the entity and save the the changes. 
        db.students.AddRange(studentList);
        
        db.SaveChanges();    
    }
}
  1. I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique.
  1. When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.
// this would be global 
private List<student> studentList = new List<student>();

public void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)
{
    var _student = new student 
    {
        Id = id,
        StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),
        StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),
        CurrentCredits = currentCredits,
        TotalCredits = totalCredits
    };
    
    studentList.Add(_student);
}


public void CommitNewStudents()
{
    // get the new students that have not been committed yet.
    var numberOfnewStudents = studentList.Count;
    
    if(numberOfnewStudents > 0)
    {
        //get the current max Id from the database.
        var maxDbId = student.NewId();
        
        for(int x =0; x < numberOfnewStudents; x++)
        {   
            // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. 
            studentList[x].Id = maxDbId + x;
        }
        
        //now, add them to the entity and save the the changes. 
        db.students.AddRange(studentList);
        
        db.SaveChanges();   
    }
}
  1. I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique.

  2. When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.

// this would be global 
private List<student> studentList = new List<student>();

public void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)
{
    var _student = new student 
    {
        Id = id,
        StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),
        StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),
        CurrentCredits = currentCredits,
        TotalCredits = totalCredits
    };
    
    studentList.Add(_student);
}


public void CommitNewStudents()
{
    // get the new students that have not been committed yet.
    var numberOfnewStudents = studentList.Count;
    
    if(numberOfnewStudents > 0)
    {
        //get the current max Id from the database.
        var maxDbId = student.NewId();
        
        for(int x =0; x < numberOfnewStudents; x++)
        {    
            // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. 
            studentList[x].Id = maxDbId + x;
        }
        
        //now, add them to the entity and save the the changes. 
        db.students.AddRange(studentList);
        
        db.SaveChanges();    
    }
}
added 2443 characters in body
Source Link
iSR5
  • 6.4k
  • 1
  • 9
  • 16

Another Update

I've checked some of your code (from the uploded source), and I noticed that you are treating all actions as INSERT. For instance, when you add new student, this is an insert action, but when you change a value of current student, this is an update action. You didn't specify anything that separates these actions.

Since you are using Entity Framework, you could use AddOrUpdate() extension which will update current records, and add new ones.

you could do this in your code :

// save BindingSource to DB
private void btnSaveToDB_Click(object sender, EventArgs e)
{
    if (bsStudents.Count != 0)
    {
        // Do UPSERT (UPDATE existing records & add new records)

        using (var context = new StudentsEntities())
        {
            var list = (IList<student>) bsStudents.DataSource;

            var studentsList = new student[list.Count];

            for (int x = 0; x < list.Count; x++)
            {
                var id = list[x].Id;


                var stud = new student
                {
                    Id = id < 1 ? x + 1 : id, //assuming that the datasource has loaded all records from DB.
                    StudentLastName = list[x].StudentLastName,
                    StudentFirstName = list[x].StudentFirstName,
                    CurrentCredits = list[x].CurrentCredits,
                    TotalCredits = list[x].TotalCredits
                };

                studentsList[x] = stud;
            }

            context.students.AddOrUpdate(studentsList);

            context.SaveChanges();

            //Rebind data
            dgvStudents.DataSource = null;

            bsStudents.DataSource = context.students.ToList();
            dgvStudents.DataSource = bsStudents;
        }



    }

}

Another thought that I saw, you are using BindingSource, it's not required in your case, you can load the db.students.ToList() directly to the datagridview datasource, and continue your work.

Another note, you modified the Entity Framework auto-generated student model class. It's okay, but keep in mind, this class will be regenarted whenever you update the Entity Framework Entities (say, you added new entities using the designer). So, I would suggest you move all modified work from the this class, to another file (you can create another partial class and move your work to it). Just try to avoid modifying on EF auto-generated classes, if you don't want to lose your work ;) ..

Another Update

I've checked some of your code (from the uploded source), and I noticed that you are treating all actions as INSERT. For instance, when you add new student, this is an insert action, but when you change a value of current student, this is an update action. You didn't specify anything that separates these actions.

Since you are using Entity Framework, you could use AddOrUpdate() extension which will update current records, and add new ones.

you could do this in your code :

// save BindingSource to DB
private void btnSaveToDB_Click(object sender, EventArgs e)
{
    if (bsStudents.Count != 0)
    {
        // Do UPSERT (UPDATE existing records & add new records)

        using (var context = new StudentsEntities())
        {
            var list = (IList<student>) bsStudents.DataSource;

            var studentsList = new student[list.Count];

            for (int x = 0; x < list.Count; x++)
            {
                var id = list[x].Id;


                var stud = new student
                {
                    Id = id < 1 ? x + 1 : id, //assuming that the datasource has loaded all records from DB.
                    StudentLastName = list[x].StudentLastName,
                    StudentFirstName = list[x].StudentFirstName,
                    CurrentCredits = list[x].CurrentCredits,
                    TotalCredits = list[x].TotalCredits
                };

                studentsList[x] = stud;
            }

            context.students.AddOrUpdate(studentsList);

            context.SaveChanges();

            //Rebind data
            dgvStudents.DataSource = null;

            bsStudents.DataSource = context.students.ToList();
            dgvStudents.DataSource = bsStudents;
        }



    }

}

Another thought that I saw, you are using BindingSource, it's not required in your case, you can load the db.students.ToList() directly to the datagridview datasource, and continue your work.

Another note, you modified the Entity Framework auto-generated student model class. It's okay, but keep in mind, this class will be regenarted whenever you update the Entity Framework Entities (say, you added new entities using the designer). So, I would suggest you move all modified work from the this class, to another file (you can create another partial class and move your work to it). Just try to avoid modifying on EF auto-generated classes, if you don't want to lose your work ;) ..

added 2408 characters in body
Source Link
iSR5
  • 6.4k
  • 1
  • 9
  • 16

Update

These are the results:

There were originally 5 students. IDs 1-5. I added 2 new students. The first one received an ID of 6. But, the second one did too.These students were did save to the dbo after a save was executed.

in short, you've executed NewId() twice before any updates. So, there were 5 records, and you've added 2 new rows (on the datagrid not the database). Those two records have not been committed to the database yet, so executing the NewId() would get the max current id from the database (which is 6). No matter how many times you execute it, as long as you've not commit any new changes, it'll always return the same value. So, either commit one row each time, and get the next max id from the database, or get the max id, then do your own counting, and commit the changes once.

For instance, your current work should store students in a collection, and whenever the user clicks save changes to the database, the application will insert the new records from that collection.

// this would be global 
private List<student> studentList = new List<student>();

public void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)
{
    var _student = new student 
    {
        Id = id,
        StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),
        StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),
        CurrentCredits = currentCredits,
        TotalCredits = totalCredits
    };
    
    studentList.Add(_student);
}


public void CommitNewStudents()
{
    // get the new students that have not been committed yet.
    var numberOfnewStudents = studentList.Count;
    
    if(numberOfnewStudents > 0)
    {
        //get the current max Id from the database.
        var maxDbId = student.NewId();
        
        for(int x =0; x < numberOfnewStudents; x++)
        {   
            // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. 
            studentList[x].Id = maxDbId + x;
        }
        
        //now, add them to the entity and save the the changes. 
        db.students.AddRange(studentList);
        
        db.SaveChanges();   
    }
}

this should cover adding new students, however, you'll need to cover the update and delete logic in your app.

Update

These are the results:

There were originally 5 students. IDs 1-5. I added 2 new students. The first one received an ID of 6. But, the second one did too.These students were did save to the dbo after a save was executed.

in short, you've executed NewId() twice before any updates. So, there were 5 records, and you've added 2 new rows (on the datagrid not the database). Those two records have not been committed to the database yet, so executing the NewId() would get the max current id from the database (which is 6). No matter how many times you execute it, as long as you've not commit any new changes, it'll always return the same value. So, either commit one row each time, and get the next max id from the database, or get the max id, then do your own counting, and commit the changes once.

For instance, your current work should store students in a collection, and whenever the user clicks save changes to the database, the application will insert the new records from that collection.

// this would be global 
private List<student> studentList = new List<student>();

public void AddStudent(int id, string firstName, string lastName, int currentCredits, int totalCredits)
{
    var _student = new student 
    {
        Id = id,
        StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1),
        StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1),
        CurrentCredits = currentCredits,
        TotalCredits = totalCredits
    };
    
    studentList.Add(_student);
}


public void CommitNewStudents()
{
    // get the new students that have not been committed yet.
    var numberOfnewStudents = studentList.Count;
    
    if(numberOfnewStudents > 0)
    {
        //get the current max Id from the database.
        var maxDbId = student.NewId();
        
        for(int x =0; x < numberOfnewStudents; x++)
        {   
            // since the id is max + 1, then we can get the count of the new students, and add 1 to the maxId. 
            studentList[x].Id = maxDbId + x;
        }
        
        //now, add them to the entity and save the the changes. 
        db.students.AddRange(studentList);
        
        db.SaveChanges();   
    }
}

this should cover adding new students, however, you'll need to cover the update and delete logic in your app.

Source Link
iSR5
  • 6.4k
  • 1
  • 9
  • 16
Loading