Can't insert simple row into DB2 w/ EF5

2019-09-02 08:27发布

问题:

I'm using EF5 and DB2 9.1 for z/OS and the IBM data provider. Everything in my program works fine except for this one part. I can't insert a new object into the database. I get the error:

{"ERROR [23502] [IBM][DB2] SQL0407N Assignment of a NULL value to a NOT NULL column \"EMPL_ID\" is not allowed."}

I have verified time after time that the value is NOT null... it's a valid integer. What's going on?

if (String.IsNullOrEmpty(emplID))
            return null;
        try
        {
            int _emplID = Convert.ToInt32(emplID.Trim());

            using (var ctx = new Data.TIMSContext())
            {
                var user = (from u in ctx.Query<Data.Entities.ASNUser>()
                            where u.EmployeeID == _emplID
                            select u).FirstOrDefault();
                if (user == null)
                {
                    //add user to database
                    user = new Data.Entities.ASNUser()
                    {
                        EmployeeID = _emplID,
                        FirstName = firstName.Trim(),
                        LastName = lastName.Trim()
                    };
                    ctx.Set<Data.Entities.ASNUser>().Add(user);
                    ctx.SaveChanges();
                }

                return new Models.UserInfo()
                {
                    EmployeeID = user.EmployeeID,
                    DisplayName = String.Format("{0}, {1}", user.LastName, user.FirstName)
                };
            }
        }
        catch (Exception e)
        {
            throw;
        }

回答1:

The problem was that I was with setting the user to a new object and then adding that to the DBSet. I guess that created two distinct copies of the user object, one null and one filled out. So I commented out the add line and it worked fine.