Linq problem with inserting new rows that have references to existing records

后端 未结 4 1757
失恋的感觉
失恋的感觉 2020-12-22 01:06

(I believe this is the same problem as this one, but there\'s no answer there, and I think I can express the problem better here...)

I have two Linq-to-SQL classes,

相关标签:
4条回答
  • 2020-12-22 01:46

    Is the State.GetState(...) function using the same datacontext as MyDataContext.GetTable<County>()?

    0 讨论(0)
  • 2020-12-22 01:59

    Solved!

    John Boker asked:

    is the State.GetState(...) function using the same datacontext as MyDataContext.GetTable() ?

    My answer was "Yes" - they are using the same DataContext class... but they were using different instances.

    Lesson learned: always use the same instance of your DataContext class for any objects you're planning to persist to your DB!

    (John gets credit for the answer, anyway...)

    0 讨论(0)
  • 2020-12-22 02:08

    Something isn't right here. I'm assuming State -> Count is a one to many relationship. In which case, the correct way of doing this is:

    State s = State.GetState("NY"); // here I do a load of a State class via the Linq DataContext
    County c = new County();
    c.Name = "Rockland";
    
    s.Counties.Add(c);
    db.SubmitChanges();
    

    Since State is the parent table, you need to add the counties to the state's counties collection.

    0 讨论(0)
  • 2020-12-22 02:12

    If the State didn't use the same DataContext instance it might work to call the Attach method first.

    0 讨论(0)
提交回复
热议问题