将更改保存到数据库时,EF数据库优先和C#-对象引用异常。尚未对数据库进行任何更改

时间:2019-03-14 15:51:37

标签: c# entity-framework

我对C#和实体框架还很陌生。 代码到达db.SaveChanges()行时出现异常。
我试图用谷歌搜索,但没有帮助。 我提供了下面的代码。 任何帮助将不胜感激。

C#代码:
这种方法是将数据插入数据库。

protected void scheduleAppointment(object sender, EventArgs e)
        {
            DentalClinicEntities1 db = new DentalClinicEntities1();
            Appointment appointment = new Appointment();
            Invoice invoice = new Invoice();
            Patient patient = new Patient();


            try
            {
                appointment.Patient_ID = Int32.Parse(txtPatientID.Text);
                appointment.Appointment_Details = txtDetails.Text;
                appointment.Appointment_Start_Date = DateTime.Parse(txtStartDate.Text);
                appointment.Appointment_End_Date = DateTime.Parse(txtEndDate.Text);
                appointment.First_Name = ddlDentist.Text;
                appointment.Created_Date = DateTime.Now;
                appointment.Created_By = Constants.Designation.Assistant_Admin.ToString();
                appointment.Modified_Date = DateTime.Now;
                appointment.Modified_By = Constants.Designation.Assistant_Admin.ToString();

                db.Appointments.Add(appointment);
                int result = db.SaveChanges();
                if (result > 0)
                {
                    MessageBox.Show("Appointment scheduled successfully !!");
                    txtPatientID.Text = string.Empty;
                    txtDetails.Text = string.Empty;
                    txtStartDate.Text = string.Empty;
                    txtEndDate.Text = string.Empty;
                    ddlDentist.SelectedIndex = 0;
                }

            }
            catch (NullReferenceException ex)
            {
                Debug.WriteLine(ex.Message);
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var eve in ex.EntityValidationErrors)
                {
                    Console.WriteLine(eve.Entry.Entity.GetType().Name, eve.Entry.State);

                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine(ve.PropertyName, ve.ErrorMessage);
                    }
                }
            }
        }

Model Code:

public partial class Appointment
    {
        public Appointment()
        {
            this.Invoices = new HashSet<Invoice>();
        }

        public int Appointment_ID { get; set; }
        public int Patient_ID { get; set; }
        public string Appointment_Details { get; set; }
        public System.DateTime Appointment_Start_Date { get; set; }
        public System.DateTime Appointment_End_Date { get; set; }
        public string First_Name { get; set; }
        public System.DateTime Created_Date { get; set; }
        public string Created_By { get; set; }
        public System.DateTime Modified_Date { get; set; }
        public string Modified_By { get; set; }

        public virtual Patient Patient { get; set; }
        public virtual ICollection<Invoice> Invoices { get; set; }
    }

Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
   System.Web.UI.ParseChildrenAttribute.GetHashCode() +26
   System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj) +23
   System.Collections.Generic.HashSet`1.InternalGetHashCode(T item) +49
   System.Collections.Generic.HashSet`1.AddIfNotPresent(T value) +34
   System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other) +131
   System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer) +125
   System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection) +49
   System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type) +155
   System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo) +236
   System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty) +71
   System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties) +1235
   System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator(Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc) +101
   System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry) +249
   System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry) +135
   System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) +100
   System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +250
   System.Data.Entity.DbContext.GetValidationErrors() +267
   System.Data.Entity.Internal.InternalContext.SaveChanges() +107
   System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +53
   System.Data.Entity.DbContext.SaveChanges() +52
   Dental_Clinic.ScheduleAppointment.scheduleAppointment(Object sender, EventArgs e) in c:\Users\Karan\Documents\Visual Studio 2012\Projects\Dental Clinic\Dental Clinic\ScheduleAppointment.aspx.cs:40
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628114
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

注册患者

我也使用相同的方法在注册病人的同时将数据插入表格。

protected void registerPatient(object sender, EventArgs e)
    {
        DentalClinicEntities1 db = new DentalClinicEntities1();
        Patient patient = new Patient();
        try
        {
            patient.First_Name = txtFirstName.Text;
            patient.Last_Name = txtLastName.Text;
            patient.Birth_Date = Convert.ToDateTime(txtBirthDate.Text);
            patient.State = listState.Text;
            patient.City = listCity.Text;
            patient.Address = txtAddress.Text;
            patient.Contact_Number = long.Parse(txtContact.Text);
            patient.Pincode = Int32.Parse(txtPincode.Text);
            patient.EmailID = txtEmail.Text;
            patient.Gender = listGender.Text;
            string issue = string.Empty;
            for (int i = 0; i < lstBoxTest.Items.Count; i++)
            {
                if (lstBoxTest.Items[i].Selected)
                    issue += lstBoxTest.Items[i].Value + ",";
            }
            patient.Medical_Issue = issue;
            patient.Type = listType.Text;
            patient.Allergies = txtAllergies.Text;
            patient.Is_Active = true;
            patient.Created_Date = DateTime.Now;
            patient.Created_By = Constants.Designation.Receptionist.ToString();
            patient.Modified_Date = DateTime.Now;
            patient.Modified_By = Constants.Designation.Receptionist.ToString();

            db.Patients.Add(patient);
            int result = db.SaveChanges();
            if (result > 0)
            {
                MessageBox.Show("Record inserted successfully!!");
                txtFirstName.Text = String.Empty;
                txtLastName.Text = String.Empty;
                txtBirthDate.Text = String.Empty;
                listState.SelectedIndex = 0;
                listCity.SelectedIndex = 0;
                txtAddress.Text = String.Empty;
                txtContact.Text = String.Empty;
                txtPincode.Text = String.Empty;
                txtEmail.Text = String.Empty;
                listGender.SelectedIndex = 0;
                lstBoxTest.ClearSelection();
                listType.SelectedIndex = 0;
                txtAllergies.Text = String.Empty;
            }
            else
            {
                MessageBox.Show("Record not inserted.");
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }
    }

0 个答案:

没有答案