-1

Context: Web Application (asp.net) using FormView to edit and insert pupil data into a SQL Server DB. Error:

System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'txtSchoolID', table 'iSAMS.dbo.TblPupilManagementPupils'; column does not allow nulls. INSERT fails.

I have an aspx page which contains a FormView control, the control contains (edit, insert and readonly) templates and buttons (for updating and inserting data). The insert uses an onclick event handler to insert a new row in the TblPupilManagementPupils table.

This table contains (amongst other columns) a primary key with the following properties:

Identity: True
Identity seed: 1
Identity Increment: 1
Data type: int
Primary key: true
Allow nulls: false

Within the codebehond file I am using the objectcontext to register the entity collection and submit the new object. See below:

protected void btnInsertCandidate_onClick(object sender, EventArgs e)
{
            //string SchoolCode = ((Label)selectedCandidateFormView.FindControl("lblCandidateKey")).Text;
            string FirstName = ((TextBox)selectedCandidateFormView.FindControl("txbFirstName")).Text;
            string LastName = ((TextBox)selectedCandidateFormView.FindControl("txbLastName")).Text;
            string PreName = ((TextBox)selectedCandidateFormView.FindControl("txbPreName")).Text;
            string Gender = ((TextBox)selectedCandidateFormView.FindControl("txbGender")).Text;
            string DOB = ((TextBox)selectedCandidateFormView.FindControl("txbCandidateDOB")).Text;
            string YoE = ((TextBox)selectedCandidateFormView.FindControl("txbCandidateYearOfEntry")).Text;
            string NCEY = ((DropDownList)selectedCandidateFormView.FindControl("ddlCandidateNCEntryYear")).SelectedValue.ToString();
            string BoardingType = ((DropDownList)selectedCandidateFormView.FindControl("ddlCandidateBoardingType")).SelectedValue.ToString();
            string Languages = ((TextBox)selectedCandidateFormView.FindControl("txbCandidateLanguage")).Text;
            string Nationalities = ((TextBox)selectedCandidateFormView.FindControl("txbCandidateNationality")).Text;

            // insert a new candidate into iSAMS (pupil record) via LINQ. Effectively copying a candidate from Admissions into a new pupil row in iSAMS.
            using (AdmissionsVerificationApplication.iSAMSEntities iSAMSContext = new AdmissionsVerificationApplication.iSAMSEntities())
            {
                TblPupilManagementPupil pupil = new TblPupilManagementPupil()
                {
                    txtForename = FirstName,
                    txtSurname = LastName,
                    txtPreName = PreName,
                    txtGender = Gender,
                    txtDOB = Convert.ToDateTime(DOB),
                    intEnrolmentSchoolYear = Convert.ToInt32(YoE),
                    intEnrolmentNCYear = Convert.ToInt32(NCEY),
                    txtType = BoardingType,
                    txtLanguage = Languages,
                    txtNationality = Nationalities
                };       

                iSAMSContext.TblPupilManagementPupils.AddObject(pupil);
                iSAMSContext.SaveChanges();
        }
}

I have also checked the .edmx file to ensure that the ID column has the correct proerties under the edmx:StorageModels tag:

    <EntityType Name="TblPupilManagementPupils">
      <Key>
        <PropertyRef Name="TblPupilManagementPupilsID" />
      </Key>
      <Property Name="TblPupilManagementPupilsID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />

......

For completeness (I think!), here's the relevant section from the generated edmx designer file:

public partial class TblPupilManagementPupil : EntityObject
{
    #region Factory Method

    /// <summary>
    /// Create a new TblPupilManagementPupil object.
    /// </summary>
    /// <param name="tblPupilManagementPupilsID">Initial value of the TblPupilManagementPupilsID property.</param>
    /// <param name="txtSchoolID">Initial value of the txtSchoolID property.</param>
    public static TblPupilManagementPupil CreateTblPupilManagementPupil(global::System.Int32 tblPupilManagementPupilsID, global::System.String txtSchoolID)
    {
        TblPupilManagementPupil tblPupilManagementPupil = new TblPupilManagementPupil();
        tblPupilManagementPupil.TblPupilManagementPupilsID = tblPupilManagementPupilsID;
        tblPupilManagementPupil.txtSchoolID = txtSchoolID;
        return tblPupilManagementPupil;
    }

    #endregion
    #region Primitive Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int32 TblPupilManagementPupilsID
    {
        get
        {
            return _TblPupilManagementPupilsID;
        }
        set
        {
            if (_TblPupilManagementPupilsID != value)
            {
                OnTblPupilManagementPupilsIDChanging(value);
                ReportPropertyChanging("TblPupilManagementPupilsID");
                _TblPupilManagementPupilsID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("TblPupilManagementPupilsID");
                OnTblPupilManagementPupilsIDChanged();
            }
        }
    }
    private global::System.Int32 _TblPupilManagementPupilsID;
    partial void OnTblPupilManagementPupilsIDChanging(global::System.Int32 value);
    partial void OnTblPupilManagementPupilsIDChanged();

.....

I read somewhere that a property IsDBGenerated may need to se set in order to instruct the mapping to use the DB for ID generation.... but as this is a generated file, I am not sure how to go about adding the property. If indeed this is the problem.

Any help wwould be greatfully received.

Regards

Barry

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • 1
    You are not settings `txtSchoolID`, I recon this a foreign key? – Jordy Langen Mar 15 '13 at 11:22
  • 1
    the exception is quite eloquent. txtSchoolID is null. I think you could have saved time just reading the exception message instead of writing a so long question – giammin Mar 15 '13 at 11:25
  • Yeah your problem isn't the insert, it's that the id has been typed string in generated code. You said this is EF4? Can you upgrade to EF5? A ton of bug fixes there. – Chris Moschini Mar 15 '13 at 11:26

1 Answers1

0

The reason is because the iSAMS.dbo.TblPupilManagementPupils table's txtSchoolID property is not being set. You need to either set the school id or set the column to allow NULL.

rhughes
  • 9,257
  • 11
  • 59
  • 87
  • Many thanks for your replies.... indeed txtSchoolID has not been set.... I was actually confusing this with TblPupilManagementPupilsID.... which of course does not need to be set! – Barry Treen Mar 15 '13 at 11:59