插入多个记录问题(linq EF)

时间:2011-10-14 21:59:47

标签: c# linq entity-framework-4 foreign-keys

我需要将多个记录插入到不同的表中,问题是某些表有2个不同的外键,EF会抛出异常。我的架构的一部分如下所示。 enter image description here

这是我的代码

  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))”之外的一切都很好。这里的问题是“agrupaciones”有2个FK(id_acreditado,id_grupo),即使我将“grupos”和“acreditados”对象添加到上下文中。 你知道发生了什么吗?实体框架是否能够在没有指定值的情况下从两个表中插入FK? 希望有人可以帮助我,谢谢

1 个答案:

答案 0 :(得分: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”。

相关问题