0

i have problem with linq2sql.

As you see below I have two tables from db - Dzieckos and Opiekuns. In Dzieckos i have idOpiekun. How to insert this idOpiekun like below, couse i have error in FK in example line.

    protected void btDodaj_Click(object sender, EventArgs e)
{
    DataClassesDataContext db = new DataClassesDataContext();
    Dziecko dz = new Dziecko();
    dz.imie = this.tbImieDz.Text;
    dz.nazwisko = this.tbNazwiskoDz.Text;
    dz.nrGrupy = Convert.ToInt32(this.dropGrupa.SelectedValue);
    Opiekun op = new Opiekun();
    op.imie = this.tbImieRodz.Text;
    op.nazwisko = this.tbNazwiskoRodz.Text;
    op.telefon = Convert.ToInt32(this.tbTel.Text);
    dz.idOpiekun = op.idOpiekun;  **//error line with FK**
    db.Dzieckos.InsertOnSubmit(dz);
    db.Opiekuns.InsertOnSubmit(op);
    db.SubmitChanges();
    Label2.Text = "Dodano " + this.tbImieDz.Text.ToString() + " " + this.tbNazwiskoDz.Text.ToString();  
}

2 Answers 2

1

you should be able to do it like this:

dz.Opiekun = op;

and remove this line:

db.Opiekuns.InsertOnSubmit(op); 
Sign up to request clarification or add additional context in comments.

Comments

1

If you have properly configured your dbml to handle the foreign key, this should work:

protected void btDodaj_Click(object sender, EventArgs e)
{
    using(DataClassesDataContext db = new DataClassesDataContext())
    {
      Dziecko dz = new Dziecko();
      dz.imie = this.tbImieDz.Text;
      dz.nazwisko = this.tbNazwiskoDz.Text;
      dz.nrGrupy = Convert.ToInt32(this.dropGrupa.SelectedValue);

      Opiekun op = new Opiekun();
      dz.Opiekun.Add(op);   //Linq to Sql will handle it
      op.imie = this.tbImieRodz.Text;
      op.nazwisko = this.tbNazwiskoRodz.Text;
      op.telefon = Convert.ToInt32(this.tbTel.Text);
      db.Dzieckos.InsertOnSubmit(dz);
      db.SubmitChanges();

      Label2.Text = "Dodano " + this.tbImieDz.Text.ToString() + " " + this.tbNazwiskoDz.Text.ToString(); 
    } 
}

2 Comments

This works for me, but I also find that I need to also do: db.Opiekuns.InsertOnSubmit(op); too, for whatever reason, sometimes my app has failed without that.
Unfortunately Opiekun dont have method Add :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.