Not updating db with EF6

ssabc

Well-known member
Joined
Dec 11, 2017
Messages
63
Programming Experience
10+
Hello:

My question is that with the code below, I am unable to update the database.
I get the following exception, as it runs through each field:

The field ____ must be a string or array type with a maximum length of ____.

As I understand things with my db, we are within the constraints. I added trim because it appeared there may be some spaces in there to truncate.

C#:
            // Get Database Records
            string IDVal = dgvJobs.CurrentRow.Cells[0].Value.ToString();
            int IDVal_int = Int32.Parse(IDVal);


            // Update database Records
            using (var db_Jobs = new ResourcePlanningEntities())
            {
                var getJobRecord = db_Jobs.Jobs.FirstOrDefault(a => a.ID == IDVal_int);


                getJobRecord.Customer = cboCustomer.ToString().Trim();
                getJobRecord.City = cboCity.ToString().Trim();
                getJobRecord.State = cboState.ToString().Trim();
                getJobRecord.Country = txtCountry.ToString().Trim();
                getJobRecord.EngineerProjectLead = cboEngineerProjectLead.ToString().Trim();
                getJobRecord.ProjectManager = cboProjectManager.ToString().Trim();
                getJobRecord.ShipDate = Convert.ToDateTime(txtShipDate.Text);


                try
                {
                    db_Jobs.SaveChanges();


                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            MessageBox.Show("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);


                        }


                    }


                }


            }
 
Primary Key and Null Value Issue??

Hello again:

I have modified the code slightly. From what I have read, this is an issue in the database where nulls are not allowed. So, I try to add them. The problem is, ID is a primary key as well, and I need to force a value there, the same value as IDVal_Int.

I am having difficulty interpreting anything but a string value in all of this!! Even the date value at the end is going to be a problem. I've been remming it out for now.


C#:
            // Get Database Records
            string IDVal = dgvJobs.CurrentRow.Cells[0].Value.ToString();
            int IDVal_int = Int32.Parse(IDVal);


            // Update database Records
            using (var db_Jobs = new ResourcePlanningEntities())
            {
                var getJobRecord = db_Jobs.Jobs.Where(a => a.ID == IDVal_int).FirstOrDefault();


                getJobRecord.ID = // What do I put here??
                getJobRecord.ProjectNumber = txtProjectNumber.ToString().Trim();
                getJobRecord.Customer = cboCustomer.ToString().Trim();
                getJobRecord.City = cboCity.ToString().Trim();
                getJobRecord.State = cboState.ToString().Trim();
                getJobRecord.Country = txtCountry.ToString().Trim();
                getJobRecord.EngineerProjectLead = cboEngineerProjectLead.ToString().Trim();
                getJobRecord.ProjectManager = cboProjectManager.ToString().Trim();
                //getJobRecord.ShipDate = Convert.ToDateTime(txtShipDate.Text);


                db_Jobs.SaveChanges(); // Not saving the data!


            }
 
Okay, so I figured this out a little, however I am back to my initial question.

Is this database somehow read only in my project? Where is this controlled?

C#:
            // Get Database Records
            string IDVal = dgvJobs.CurrentRow.Cells[0].Value.ToString();
            int IDVal_int = Int32.Parse(IDVal);


            // Update database Records
            using (var db_Jobs = new ResourcePlanningEntities())
            {
                var getJobRecord = db_Jobs.Jobs.Where(a => a.ID == IDVal_int).FirstOrDefault();


                getJobRecord.ID = IDVal_int;
                getJobRecord.ProjectNumber = txtProjectNumber.ToString().Trim();
                getJobRecord.Customer = cboCustomer.ToString().Trim();
                getJobRecord.City = cboCity.ToString().Trim();
                getJobRecord.State = cboState.ToString().Trim();
                getJobRecord.Country = txtCountry.ToString().Trim();
                getJobRecord.EngineerProjectLead = cboEngineerProjectLead.ToString().Trim();
                getJobRecord.ProjectManager = cboProjectManager.ToString().Trim();
                //getJobRecord.ShipDate = Convert.ToDateTime(txtShipDate.Text);
                
                // Write to Database
                db_Jobs.SaveChanges(); // Not saving the data!


            }
 
How EXACTLY are you determining that the data is not being saved? If you call SaveChanges then there are really only three possible outcomes:

1. There are changes to save, the call succeeds and the changes are saved.
2. The call succeeds but there were no changes to save.
3. The call fails and an exception is thrown.

If no exception is thrown then I don't see how it's possible that you have changes to save but they are not saved. A common problem is that people are using a local database, i.e. a data file that is part of their project, and they end up looking in the wrong database for the data changes, thus thinking that they have not been saved. If you are using a local database, I suggest that you read the following to learn how they are managed:

https://msdn.microsoft.com/en-us/library/ms246989.aspx
 
jmc:

I am not dealing with a local database here. Though there is an instance on my PC of SQL Express that is being used. My interpretation of your local definition is that it is art of my project.

In the illustration below, I have changed the value STOCK to STOCK 2. Somehow, the exception is that the length of the filed is being violated, which it is not. This is why I have added all the trim stuff.
Screen Shot 04-23-18 at 09.25 AM.PNG

Next I add a City and State, and it does not like this either.

Screen Shot 04-23-18 at 09.29 AM.PNG

Finally, here is my database.

Screen Shot 04-23-18 at 09.33 AM.PNG

I believe the database is connecting and function, as the field to delete data works great. As a reminder, I am using ef6.

Much thanks!
 
There's a lot of information there that you didn't provide in the first place. There also seem to be two separate issues there. The first screenshot is occurring in a DataGridView that is apparently bound to a DataTable, which seems strange if you're using EF. That error message is referring to the MaxLength property of the Customer DataColumn, which may or may not be the same as the size of the corresponding column in the database. The seconds screenshot doesn't specify what validation rule was violated, so it may or may not be that same column at issue, but it does instruct you to see the EntityValidationErrors property for more information. Have you done that?
 
jmc:

1. I am trimming the value. The length is 7 characters, and the db allotment is 30. This leads me to think it's something else.

2. Entity Validation Errors property. Not sure what that is, but I will look into it.

Thanks!
 
1. I am trimming the value. The length is 7 characters, and the db allotment is 30. This leads me to think it's something else.
When are you trimming it? The error message that we can confirm relates to the text length is happening in the grid and that's nothing to do with EF.
2. Entity Validation Errors property. Not sure what that is, but I will look into it.
The Exception Assistant window has a View Details link so that you can view the details of the exception. That's basically a PropertyGrid for the exception, so that EntityValidationErrors property will be accessible there. It's always best to read everything the IDE shows you and if it provides access to more information then avail yourself of that access.

I've just looked more closely at your code and I can see the issue. This demonstrates perfectly why you need to actually debug your code rather than just reading it. Even without a breakpoint, you could have just moused-over getJobRecord.Customer to see whether it contained what you expected it to. Had you done that, you'd have seen that it didn't. None of your record properties would because you're assigning the wrong values to them. Concentrating on the Customer property, you have this:
getJobRecord.Customer = cboCustomer.ToString().Trim();

You're calling ToString on the ComboBox itself. That does not get the data contained in the control. The same goes for your TextBoxes. I'm not going to tell you what to change that to because, if you don't already know, this will be a good exercise in finding information. You should use the Help menu in VS to open the documentation and then read about the ComboBox control and the TextBox control to see what members they have and work out which one will get you the data you want.

You should also learn how to debug your code sooner rather than later. Start here:

https://msdn.microsoft.com/en-us/library/y740d9d3.aspx
 
Back
Top Bottom