how to save data to relationship table with LINQ to SQL?

Last post 06-27-2009 3:38 AM by maverickhyd. 1 replies.

Sort Posts:

  • how to save data to relationship table with LINQ to SQL?

    06-26-2009, 1:54 PM
    • Participant
      1,018 point Participant
    • KentZhou
    • Member since 05-03-2006, 3:48 PM
    • Posts 573

    Suppose I have three tables: Tab1(Cola, ,,,,) Tab2(Colb,....), tab3(cola, colb,...)

    Cola is primiary key for tab1, colb is primary key for tab2.  Tab3 is a relationship of tab1 and tab2, so cola, colb is foreign keys for tab3.

    For tab1 and tabl2, becuase thery are entity, so I can use datacontext db to add a new instance like:

    db.Tab1s.InsertOnSubmit( tab1 obj);

    db.Save();


    db.Tab2s.InsertOnSubmit(tab2 obj);

    db.Save();

     But When I try to insert data to tab3 in simiar way:

    db.Tab3s.InsertOnSubmit(tab3 obj);

    I got exception eroro said that tabl3 has no primiary key.  tab3 only have a index on cola, colb:

    -        ex    {"Can't perform Create, Update or Delete operations on 'Table(Tab3)' because it has no primary key."}    System.Exception {System.InvalidOperationException}

    How to resolve this issue?



  • Re: how to save data to relationship table with LINQ to SQL?

    06-27-2009, 3:38 AM
    Answer
    • Contributor
      2,397 point Contributor
    • maverickhyd
    • Member since 03-25-2009, 2:38 AM
    • Posts 416

    In LINQ to SQL, all your entities should have a primary key column defined. If you don't define an entity without a primary key, you can only fetch its instances from database. You won't be able to make any changes to it. This is mainly because LINQ to SQL uses an Identity-Map to cache and keep track of the entities it is managing.

    Check this

    http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/f3b216d2-fa06-49a1-a901-11702e80b38c

    Please Mark as Answer if it helped You!
Page 1 of 1 (2 items)