none
Problem with LINQ in adding relational data RRS feed

  • Question

  • I have three tables

    1) Parent

    2) Child

    3) Parent-Child relations

    reason why I have the third table and not just a parent Id in child table is that a child doesnt necessarily needs to have a parent ..

    I am using LINQ and basically if I add Child and Parent as seperate entities .. everything works fine but when I try to add a Child which should be linked to a Parent .. things dont work as smooth .. this is how I am doing it

    FIRST APPROACH

    //lets say the parent already exists and I am creating a child and linking it to the parent

     

    //set child properties

    ChildA.name = 'Some Name';

    ChildA.CreatedDate = Today;

    //add to data context

    dataContext.InsertOnSubmit(ChildA);

    //save

    dataContext.Save();

     

    //then I am setting up the connection in the relation table

    RelationA.Child = ChildA;

    RelationA.Parent = ParenA;

    dataContext1.Add(RelationA);

    dataContext1.Save();

     

    When I do this, it ends up adding two children with one of them linked to the parent and the other isnt

     

    SECOND APPROVAL

    I basically just didnt do the save twice .. instead I did the Child save after creating the Relation entry ..

    This time, it ends up adding another Parent entry to db with same properties as original parent ..

     

    Can anyone see what I am doing wrong or may be suggest a better way to handle this

    Thanks
    Wednesday, July 15, 2009 1:44 PM

All replies

  • hi, adeelmahmood Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals 
     you say   "why I have the third table and not just a parent Id in child table is that a child doesnt necessarily needs to have a parent "
    then you can set parent ID in child table if a child doesn't have a parent you can set this ID be NULL , if i can search information in one table , i would not search one more table,this is my advice.

    ps  i'm not good at this , others' advices may be more helpful

    freshman

     
    Thursday, July 16, 2009 12:53 AM
  • thanks for ur reply ..
    I agree that wat u suggested does makes things simple and probably solves my problem too .. but in my current design I have the flexibility to assign a single child to multiple parents and vice versa .. so a many to many relationship ..
    but I guess if I cant find a solution to my problem (which I still havent) I will probably do as u suggested .. so thanks
    Thursday, July 16, 2009 2:44 AM