taelor
taelor

Reputation: 639

Linq to Sql Parent Child

ok, so I new to the C# way of doing things, I come from the ruby world.

I have a one to many relationship, (parent to children for sake of this question), and for some reason L2S was wanting to create a new parent instead of using the one is already had. 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

that works just fine.

Can someone explain to me whats going on?

PS. Parent was found from the database using L2S. all the keys and such are set up properly. Thanks for any insight.

Upvotes: 3

Views: 4125

Answers (4)

user68610
user68610

Reputation: 169

Have you tried

parent.Children.Add(new_Child);

// other stuff

// Submit changes.

Upvotes: 1

RobS
RobS

Reputation: 9422

The ORM (SqlMetal or via a DBML) models a Parent object (and you'll also notice a collection of Children on the Parent Entity also).

However, the entity retains a property representation of the foriegn key column (in this case ParentId) which can also be assigned to.

This can be helpful if you only know the ID of the parent (instead of having loaded the parent entity via your DataContext).

AFAIK there's no immediate drawback to use of direct assignment (e.g. Child.Parent = Parent) or via assignment of ID (e.g Child.ParentID = ID) as long as (obviously) the ID you are trying to assign belongs to a valid row in the Parent table.

Upvotes: 0

dkarzon
dkarzon

Reputation: 8038

you could possiblly 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 maybe just make the 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();

Upvotes: 2

eglasius
eglasius

Reputation: 36037

Both of these should work:

//option 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();
}

//option 2:

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

Upvotes: 2

Related Questions