How to best assign object relationships in LinqToSql
Lets assume the simple case, a simple relationship between table A and table B, where B has开发者_C百科 an A_Id field in it.
Now, assume I have an object of type A (currentA), and am creating a brand new B object.
B newB = new B() { A_id = currentA.Id };
Is this the correct way to set that relationship? Or should I do:
B newB = new B() { A = currentA };
In the second case, does B.A_Id get set automatically?
Perhaps I need to explicitly set both?
B newB = new B() { A = currentA, A_Id = currentA.Id };
I am looking for the most elegant way to set this new relationship such that I can correctly save it to the database later, and can exploit it immediately... for example I might want to do:
MessageBox(String.Format("B's parent is now {0}", B.A.Name));
It was not intuitive to me at first, but the answer is to:
currentA.Bs.Add(new B());
It seems that if you Add an object to an EntitySet, it will take care of assigning the appropriate relationship properties on the Added object.
精彩评论