如何在一个表中插入数据并在asp.net mvc 5&amp ;;中更新另一个表中的一些数据。实体框架

时间:2017-12-06 08:16:54

标签: entity-framework asp.net-mvc-5

我正在为我的文具项目使用ASP.NET MVC 5和Entity Framework。我的实体模型是(我只给出了重要的字段)。

public partial class Purchase
{
    public int Id { get; set; }
    public string Item { get; set; }
    public int Quantity { get; set; }
    public Nullable<decimal> UnitPrice { get; set; }
    public Nullable<decimal> Amount { get; set; }
    public System.DateTime PurchaseDate { get; set; }
    public string Vendor { get; set; }       
    public string ChallanNo { get; set; }
    public string BillNo { get; set; }     
}
public partial class Stock
{
    public int MatId { get; set; }
    public string Item { get; set; }
    public Nullable<int> Quantity { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<int> UserId { get; set; }
    public string Status { get; set; }
    public Nullable<System.DateTime> SystemDate { get; set; }
}

现在要求是我创建采购订单时,它会将数据插入到采购表中。现在我必须自动更新数量字段的Stock表。

1 个答案:

答案 0 :(得分:0)

保存购买时更新库存表。假设您要保存的购买是对象模型

using (var context=new SomeDBContext()){
  context.Purchases.Add(model);
  var itemRow=context.Stocks.FirstOrDefault(o=>o.item==model.item);
  if (itemRow !=null)
  {
     itemRow.Quantity+ =model.Quantity;
     context.Entry(itemRow).State=EntityState.Modified;
  }
  else
  {
     context.Stocks.Add(new stock(){Item=model.Item,Quantity=model.Quantity,.......});
  }
     context.SaveChanges();
}

注意:
1。您需要实施另一个代码来更新和删除购买 2.最好的方法是计划您的表格,以便在库存和购买之间存在主要的详细关系,以便您可以在其详细信息下使用所有购买的总和更新库存数量。这样,您可以在数量更改时从采购数量属性设置器中更新库存(主数据)