tags:

views:

1088

answers:

4

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.

A: 

Have you tried

parent.Children.Add(new_Child);

// other stuff

// Submit changes.

+2  A: 

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();
}
eglasius
+2  A: 

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();
d1k_is
+1 y, was so focused on the question that just carried the submitchanges as in the posted sample. That said, it doesn't technically do a single db call.
eglasius
so, the db.SubmitChanges() on the outside of the loop doesn't batch things up?
taelor
Yeh, i guess thats true,. outside the loop just wraps it up more, like a batch, each to his own i guess...
d1k_is
A: 

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.

RobS