在MVC中使用Linq更新字段
我正在开发一个用于仓库管理的MVC应用程序,当我收到产品时需要更新我的库存表,特别是库存字段,当我需要增加库存字段以及发送产品时我需要打折的股票领域,我只能够添加新行)和我要的是更新的行(仅域Stock)所附照片Table Inventario在MVC中使用Linq更新字段
我的控制器[发布]:
//CREAMOS/DECLARAMOS LA TRANSACCION
using (var transaccion = db.Database.BeginTransaction())
{
try
{
//CARGO LOS DATOS A RECEPCION
Recepcion recepcion = new Recepcion
{
Kn_CodigoProveedor = proveeid,
Kn_CodigoBodega = bodeid,
UserId = usuaid,
f_Ingreso = fingreso,
f_Factura = ffactura,
f_Guia = fguia,
n_Guia = nguia,
n_Factura = nfactura,
n_OrdenCompra = nordencompra,
};
db.Recepcions.Add(recepcion);
db.SaveChanges();
//RECUPERO EL ULTIMO ID QUE GENERO (ULTIMA RECEPCION)
ultimarecepcionid = db.Recepcions.ToList().Select(r => r.Kn_CodigoRecepcion).Max();
//CICLO QUE GUARDA CADA ELEMENTO DEL DETALLE
foreach (ProductosRecepcion item in recepcionview.ProductosList)
{
var detalle = new RecepcionDetalle()
{
Kn_CodigoRecepcion = ultimarecepcionid,
Kn_CodigoProducto = item.Kn_CodigoProducto,
Foto = item.Foto,
d_Cantidad = item.d_Cantidad,
Precio_Unitario = item.Precio_Unitario,
};
//CARGO EL OBJETO AL DETALLE
db.RecepcionDetalles.Add(detalle);
foreach (ProductosRecepcion item1 in recepcionview.ProductosList)
{
//RECUPERO ULTIMO STOCK (TABLA INVENTARIO)
UltimoStock = db.Inventarios.Where(b => b.Kn_CodigoBodega == bodeid).Where(p => p.Kn_CodigoProducto == item.Kn_CodigoProducto).ToList().Select(p => p.Stock).Max();
}
//ARMO EL OBJETO PARA ACTULIZAR MI TABLA INVENTARIO
var stock = new Inventario()
{
Kn_CodigoProducto = item.Kn_CodigoProducto,
Kn_CodigoBodega = bodeid,
Stock = (detalle.d_Cantidad + UltimoStock),
};
//GUARDO
db.Inventarios.Add(stock);
}
db.SaveChanges();
//CONFIRMAMOS EXITO DE TRANSACCION
transaccion.Commit();
}
catch (Exception ex)
{
//CONFIRMAMOS FRACASO DE TRANSACCION
transaccion.Rollback();
ViewBag.Error = "ERROR: " + ex.Message;
return View(recepcionview);
}
}
对不起,我的英语,对我有帮助吗?
根据我的理解,您必须通过增加或减少“库存”列来更新库存水平。
但是你插入代码中的新纪录:
var stock = new Inventario()
{
Kn_CodigoProducto = item.Kn_CodigoProducto,
Kn_CodigoBodega = bodeid,
Stock = (detalle.d_Cantidad + UltimoStock),
};
//GUARDO
db.Inventarios.Add(stock);
这是你应该做的:
-
得到你想要更新(通过检索它)记录
var stockItem = db.Inventarios(s => s.ReplaceBYYourField == replaceBYYourValue).FirstOrDefault();
-
更新通过增加或减少股票值的记录:
stockItem.Stock + = 1;
-
保存变化:
db.Entry(stockItem).STATE = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
该代码遵循EF版本4.在新版本中,语法可能不同,但在我提到的步骤中适用相同的逻辑。让我知道你正在使用哪个EF版本,这样我就可以更新我的答案。
不适用语法...必须使用我的EF版本....我的版本是5 @编码 –
然后,您必须使用Attach方法,检查这些链接[EF5](https://msdn.microsoft.com /en-us/library/jj592676(v=vs.113).aspx)和这[SO](https://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record) – Coding
你有什么具体问题? – Shyju