Gayashan
Gayashan

Reputation: 351

How to add data to ObservableCollection in entity framework?

I have a table in my databse called Impacts, and it has two foring keys called cmpt_name and cmpt_reference from Component Table.

and i want to add some data to a ObservableCollection which i created using Impact table. But i cant add cmpt_name and cmpt_reference to it ?

public ObservableCollection<Impact> ModelListe { get; set; }

private Impact model;

public Project_Questions_Window()
{
    InitializeComponent();

    ModelListe = new ObservableCollection<Impact>();
    DataContext = this;
}

public void addData()
{
     model = new Impact();
     **model.Component.cmpt_name = comboBoxComponents.Text;**
     model.impt_name = textBoxQuestion.Text;
     **model.Component.cmpt_reference = comboBoxComponents.SelectedValuePath;**
     ModelListe.Add(model);
}

I get error in highlighted line it says:

Object reference not set to an instance of an object.

Can any one tell me how to solve it please? Im using entity model database.

Upvotes: 0

Views: 913

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109137

When you new up an Impact instance I'm pretty sure it does not contain a Component yet. So model.Component is the null object here.

I don't know your business logic but I assume the remedy is to fetch Components from the database and populate the combobox with these pre-existing components. Now when you create a new Impact you don't set its component's name, but you set its Compenent property:

model.Component = comboBoxComponents.SelectedValue;

Upvotes: 1

Related Questions