2011-10-14 124 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