2016-02-24 15 views
2

我使用ASP.NET 5實體框架7. 我有這個型號:子元素在實體框架插入7

public class ParentModel 
{ 
    public Guid Id { get; set; } 
    public virtual ChildModel Children { get; set; } 
} 

public class ChildModel 
{ 
    public Guid Id { get; set; } 

    public virtual AnotherChildModel AnotherChild { get; set; } 
} 

public class AnotherChildModel 
{ 
    public Guid Id { get; set; } 

    public string Text { get; set; } 
} 

當我試圖ParentModel添加到數據庫中,這不是」自動不要再增加ChildModel和AnotherChildModel數據庫,而ParentModel代碼完全正確,例如:

var parent = new ParentModel() { Children = new ChildModel() { AnotherChild = new AnotherChildModel() { Text = "sometext" }}}; 

所以,簡單parentSet.Add(parent)不起作用,有另一種方式,除了手動添加所有型號的套?

編輯:

例外,我有:

DbUpdateException: An error occurred while updating the entries. See the inner exception for details. 
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ParentModel_ChildModel_ChildrenId". The conflict occurred in database "aspnet5-WebApplication1-922849d0-b7da-4169-8150-9a2d05240a47", table "dbo.ChildModel", column 'Id'. The statement has been terminated. 
+0

不,你需要添加子和父類單獨 –

+1

您正在使用的初始化'ChildModel'似乎並不模型... – David

+0

@大衛編輯以 –

回答

2

在EF7的電流RC1版本,Add()只有遞歸增加附着物在集合(即真孩子),不參考實體,與EF6一樣。

所以,如果你有以下的模型(這是與您所選擇的名稱更加一致)...

public class ParentModel 
{ 
    public Guid Id { get; set; } 
    public virtual ICollection<ChildModel> Children { get; set; } 
} 

......孩子們也將通過單個語句parentSet.Add(parent)增加。

我不知道這是否是有意的行爲。 RC已經被證明會出現一個「釋放候選人」不應該擁有的問題。但也許這是一個面向OO的設計決定,父母封裝他們的孩子,而不是相反。

+0

非常奇怪的行爲,當我只能添加ChildModel的集合,而不是僅添加ChildModel。如果我想添加引用的實體,比如Child和AnotherChild,我該怎麼做? –

+0

你必須明確地添加它們,就像添加「父」一樣。 –

+0

我理解正確嗎,與級聯刪除相同的情況? –