views:

59

answers:

2

Hello, 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();  
}
+1  A: 

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(); 
    } 
}
Alex Bagnolini
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.
Brian
Unfortunately Opiekun dont have method Add :/
netmajor
+1  A: 

you should be able to do it like this:

dz.Opiekun = op;

and remove this line:

db.Opiekuns.InsertOnSubmit(op); 
klausbyskov
Tnx! Works perfect!!
netmajor