2013-08-23 54 views
0

技術:ASP.NET MVC3,實體框架4,多層應用程序實體框架1到0的關係

我有兩個表在0到1的關係。重複數據可以有0個或1個pagamento,而pagamento只有一個重複數據。 Link

的Duplicata的行IM救了我的數據庫,當我創建一個新的Pagameto實體,並加入到一個Dupliacata給出了這樣的埃羅:

A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. 

圖像波紋管顯示實體Duplicata一個Pagamento。 Link

並與代碼獲取錯誤:

  context.Duplicata.Attach(duplicata); 
      context.ObjectStateManager.ChangeObjectState(duplicata, EntityState.Modified); 

      context.SaveChanges(); 
+0

爲什麼使用attach?你以前是否分離過實體?因爲如果您想要執行保存操作,請嘗試使用.AddObject方法代替 – Gonzix

+0

我使用attach,因爲複製數據已經存在於我的數據庫中。在這種情況下,我添加一個pagamento重複數據。 – Ramalho

回答

0

是的,但附加的porpouse不添加元素到duplicata府進入上下文分離實體。如果你想創建一個新的複製數據,只需創建一個新數據副本。像

// just for testing NO magic numbers! 
var pagamentoId = 1; 
var duplicata = new Duplicata(); 
duplicata.PAGAMENTO_ID = pagamentoId; 
duplicata.VALOR = 1000; 
duplicata.CLIENTE_ID = 23; 

// add the rest of properties 


// then... 
context.AddObject("Duplicatas", duplicata); 
context.SaveChanges(); 

注意我在ADDOBJECT使用「Duplicatas」我認爲這是你的Duplicata集(集意味着它Duplicata的集合,並設置在EDMX文件名)的名字。

通過將pagamento_id設置爲所需的值,它會自動生成兩個實體之間的關係

+0

但我的問題是當我創建一個Pagamento,並將pagamento添加到任何Duplicata。 – Ramalho

+0

但是,根據您的數據庫設計,duplicateata取決於pagamento(duplicata是pagamento的父級),並且該關係在dbo.pagamento.id和dbo.duplicata.pagamento_id之間完成。如果情況並非如此,pagamento是父母,你必須重新設計數據庫。所以如果我說的是正確的,你必須首先創建pagamento並添加一個重複數據。 – Gonzix

+0

所以這是在數據庫的設計中的一個錯誤。我需要那個Pagamento取決於Duplicata,不然。 比我需要的是重做Duplicata和Pagamento之間的關係和duplicata.pagamento.add(Pagamento)將工作正確嗎? – Ramalho