EF Database First и C # - Object Reference Исключение при сохранении изменений в базе данных.Не внесено никаких изменений в базу данных - PullRequest
1 голос
/ 14 марта 2019

Я довольно плохо знаком с C # и структурой сущностей.Я получаю исключение, когда код достигает строки db.SaveChanges ().
Я пытался найти его в Google, но это не помогло.Я предоставил код ниже.Мы будем благодарны за любую помощь.

Код 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);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...