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

后端 未结 4 1777
失恋的感觉
失恋的感觉 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 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.

提交回复
热议问题