简体   繁体   中英

How do I add a new text value from a WPF textbox to a database using the Entity Framework?

I have a problem with adding text to the database, namely I have three tables:

enter image description here

In WPF, the registration looks like this:

enter image description here

In buttonSend I added such a code:

private void ButtonRegister_Click(object sender, RoutedEventArgs e)
{
        model.Imie = Imie.Text.Trim();
        model.Nazwisko = Nazwisko.Text.Trim();
        model.Pesel = PESEL.Text.Trim();
        model.Adres.Ulica = Ulica.Text.Trim();
        model.Adres.Numer_domu = NumerD.Text.Trim();
        model.Adres.Numer_mieszkania = NumerM.Text.Trim();
        model.Kontakt.Telefon = Telefon.Text.Trim();
        model.Kontakt.email = Email.Text.Trim();

        using (eDoctorEntities db = new eDoctorEntities())
        {
            db.Pacjents.Add(model);
            db.SaveChanges();
        }

        MessageBox.Show("Zarejestrowano !");
}

The program throws an error:

System.NullReferenceException: 'The object reference has not been set to the instance of the object.'

on the line

model.Adres.Ulica = Ulica.Text.Trim();

How to fix this? Please help me.

you must first add adress model then add to model clas like this code :

        model.Imie = "your text";
        model.Nazwisko = "your text";
        model.Pesel = "your text";
        Adres adres = new Adres();
        adres.Ulica = "your text";
        adres.Numer_domu = "your text";
        adres.Numer_mieszkania = "your text";
        model.Adress = adres; 
...

and your model classes like this classes:

 public class Model
{
    public string Imie { get; set; }
    public string Nazwisko { get; set; }
    public string Pesel { get; set; }
    public Adres Adress { get; set; }
}

public class Adres
{
    public string Ulica { get; set; }
    public string Numer_domu { get; set; }
    public string Numer_mieszkania { get; set; }
}
...

Before setting

model.Adres.Ulica = Ulica.Text.Trim();

you should initialize Adres

model.Adres = new Adres();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM