Linq to Sql Parent Child

ok, so I'm new to C # to do something, I'm from the ruby ​​world.

I have a one-to-many relationship (parent for children for the sake of this question), and for some reason L2S wanted to create a new parent instead of using the one that already was. Here is the code.


Console.WriteLine(parent.Id); // this equals 1
foreach (string names in names)
{
    Child new_child= new Child();
    new_child.Parent = parent;//now parent.Id would equal the next in the sequence.
    new_child.Name= name


    db.CommitLogs.InsertOnSubmit(new_child);
    db.SubmitChanges();
}

but if i just say

new_child.ParentId = parent.Id

which works great.

Can someone explain to me what is going on?

PS. The parent was found from the database using L2S. all keys, etc. configured correctly. Thank you for understanding.

+3
source share
4 answers

you could do it as Freddy said:

foreach (string names in names)
{
    Child new_child= new Child();
    new_child.Name= name
    parent.Children.Add(child);
    db.SubmitChanges();
}

But it is possible to simply make a 1 DB call outside the foreach loop:

foreach (string names in names)
{
    Child new_child= new Child();
    new_child.Name= name
    parent.Children.Add(child);
}
db.SubmitChanges();
+2
source

:

// 1:

foreach (string names in names)
{
    Child new_child= new Child();
    new_child.ParentId = parent.Id;//now parent.Id would equal the next in the sequence.
    new_child.Name= name

    db.CommitLogs.InsertOnSubmit(new_child);
    db.SubmitChanges();
}

// 2:

foreach (string names in names)
{
    Child new_child= new Child();
    new_child.Name= name
    parent.Children.Add(child);
    db.SubmitChanges();
}
+2

parent.Children.Add(new_Child);

//

// .

0

ORM (SqlMetal DBML) ( Children on the Parent Entity).

foriegn ( ParentId), .

, ( , DataContext).

AFAIK (, Child.Parent = Parent) (, Child.ParentID = ID) , () , , .

0

Source: https://habr.com/ru/post/1705219/


All Articles