【问题标题】:How do I add a new text value from a WPF textbox to a database using the Entity Framework?如何使用实体框架将 WPF 文本框中的新文本值添加到数据库?
【发布时间】:2018-06-10 09:57:06
【问题描述】:

我在向数据库中添加文本时遇到问题,即我有三个表:

enter image description here

在 WPF 中,注册如下所示:

enter image description here

在buttonSend中我加了这样一段代码:

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 !");
}

程序抛出错误:

System.NullReferenceException: '对象引用尚未设置到对象的实例。'

上线

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

如何解决这个问题?请帮帮我。

【问题讨论】:

  • 也许您将 null 或空传递给该字段,因此您收到此错误。
  • 你在哪里创建模型?变种模型 = 新的 BlaBlaClass();在方法中添加这个。所以请分享模型类。
  • @codelover Pacjent model = new Pacjent(),它与全局对象存在于同一个类中

标签: c# wpf entity-framework


【解决方案1】:

设置前

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

你应该初始化 Adres

model.Adres = new Adres();

【讨论】:

  • 谢谢!这是解决方案! +1 喜欢 :)
  • 所以你可以添加“this.Adres = new Adres();”在 Pacjent 类的构造函数中。
【解决方案2】:

您必须先添加地址模型,然后添加到模型类,如下代码:

        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; 
...

你的模型类像这样的类:

 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; }
}
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多