2011-10-14 120 views
2

我需要將多個記錄插入到不同的表中,問題是某些表有兩個不同的前綴鍵,EF會引發異常。下面顯示了我的模式的一部分。 enter image description here插入多個記錄問題(linq EF)

這是我的代碼

Credito cred = new Credito() 
      { 
       Producto = credito.producto, 
       Tipo = credito.tipo, 
       Status = credito.status, 
       Cantidad = credito.monto_prestamo, 
       TasaInteres = credito.tasa_interes, 
       Plazo = credito.plazo, 
       Periodo = credito.periodo, 
       FechaInicio = credito.fecha_inicio 
      }; 
      Cuentas cuenta = new Cuentas() 
      { 
       IDCredito = credito.idCredito, 
       IDBanco = credito.idBanco 
      }; 
      Grupo gpo = new Grupo() 
      { 
       Nombre = credito.grupo, 
       IDRepre = credito.idRepGpo 
      }; 

      context.creditos.AddObject(cred); 
      context.bancos_credito.AddObject(cuenta); 
      for (int i = 0; i < credito.total_plazo; i++) 
       context.amortizaciones.AddObject(AgregaAmortizacion(ref fechaPago, i, credito)); 
      context.grupos.AddObject(gpo); 
      for (int i = 0; i < renglones; i++) 
      { 
       context.acreditados.AddObject(AgregaAcreditado(i, credito)); 
       context.agrupaciones.AddObject(AgregaAgrupacion(i, credito)); 
      } 
      context.SaveChanges(); 

一切,但 「context.agrupaciones.AddObject(AgregaAgrupacion(I,CREDITO))」 是好的。這裏的問題是,即使當我將「grupos」和「acreditados」對象添加到上下文時,「agrupaciones」也有2 FK(id_acreditado,id_grupo)。 你知道發生了什麼嗎?如果沒有指定值,實體框架是否無法從兩個表中插入FK? 希望有人能幫助我,謝謝

+0

你能發佈異常消息嗎? – GianT971

+0

順便說一下,什麼是「AgregaAgrupacion」? – GianT971

+0

@ GianT971 AgregaAgrupacion是一個函數,它從數組獲取數據並返回「agrupaciones」類型,與「AgregaAcreditados」相同。我有我的視覺工作室西班牙語,但異常的翻譯會是這樣的:「關係的主要目的'SACREDIModel.FK_agrupaciones_acreditados'無法確定。有可能兩個或更多的實體具有相同的主鍵」 –

回答

0

它看起來像問題是你只設置FK ID(IDRepre,IDBanco)。通常在EF中設置引用時,使用整個對象(cuenta.Credito = cred;)。

Credito cred = new Credito() 
     { 
      Producto = credito.producto, 
      Tipo = credito.tipo, 
      Status = credito.status, 
      Cantidad = credito.monto_prestamo, 
      TasaInteres = credito.tasa_interes, 
      Plazo = credito.plazo, 
      Periodo = credito.periodo, 
      FechaInicio = credito.fecha_inicio 
     }; 
Cuentas cuenta = new Cuentas() 
     { 
      IDCredito = credito.idCredito, 
      IDBanco = credito.idBanco 
     }; 
cred.Cuentas.Add(cuenta); 
... (more mapping code here) 
context.credito.AddObject(cred); 
context.SaveChanges(); 

如果孩子設置正確,您只需要爲父對象執行「AddObject」。

+0

事實上,我爲所有孩子設置參考,除了依賴於「grupo」和「acreditados」的「agrupaciones」,這就是爲什麼我要在「acreditados」和「grupos」之後添加「agrupaciones」對象的原因。如果我評論「context.agrupaciones.AddObject(AgregaAgrupacion(i,credito));」線我沒有問題 –

+0

我會改變這一行gpo.Agrupaciones.Add(AgregaAgrupacion(我,credito));這給它與它有關的grupos對象的上下文。 –

+0

如果我得到它的權利,我應該編碼以下內容:context.creditos.AddObject(cred); cred.bancos_credito.Add(cuenta); for(int i = 0; i