2009-03-24 2 views
3

좋아, 그래서 일을하는 C# 방식에 새로운, 나는 루비 세계에서 왔어.Linq to SQL 상위 부모

나는 (이 질문을 위해 부모와 자녀가) 1 대 1의 관계를 가지고 있으며, L2S는 이미 사용 된 대신 새로운 부모를 만들고 싶어했습니다. 여기에 코드가 있습니다.


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

하지만 난 그냥 잘 작동

new_child.ParentId = parent.Id 

을 말한다면.

누군가 나에게 설명 할 수 있습니까?

추신. 부모는 L2S를 사용하여 데이터베이스에서 발견되었습니다. 모든 키 등이 올바르게 설정됩니다. 어떤 통찰력에도 감사드립니다.

답변

2

당신이 프레디로 할 possiblly 수 있다고 말했다 :

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

하지만 어쩌면 단지 1 DB 외부에서 전화를 걸 수 있습니다.

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

+1 y는 게시 된 샘플에서와 같이 submitchanges를 방금 전송 한 질문에 너무 집중했습니다. 즉, 기술적으로 단일 db 호출을 수행하지는 않습니다. – eglasius

+0

그래서 루프 외부의 db.SubmitChanges()는 일괄 처리하지 않습니까? – taelor

+0

예, 그렇습니다. 루프 바깥 쪽은 배치와 같이 더 많이 감싸고 있습니다. 각자 자신의 것으로 추측합니다. – dkarzon

0

시도해 보셨습니까?

parent.Children.Add (new_Child);

// 기타 내용

// 제출 변경.

2

이 두 가지 일을해야합니다

// 옵션 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(); 
} 
0

ORM (SqlMetal 또는 DBML를 통해) 모델 부모 개체 (당신은 또한 부모 엔티티에 대한 아동의 컬렉션을 알 수 있습니다) : 그는 루프를 foreach는.

그러나 엔티티는 지정할 수도있는 foriegn 키 열 (이 경우 ParentId)의 속성 표현을 유지합니다.

이것은 (DataContext를 통해 상위 엔티티를로드하는 대신) 상위 ID 만 알고있는 경우 유용 할 수 있습니다.

AFAIK 할당하려는 ID가 속한 한 직접 할당 (예 : Child.Parent = Parent) 또는 ID 할당 (예 : Child.ParentID = ID)의 직접적인 단점은 없습니다. Parent 테이블의 유효한 행