实体框架在一个表中插入并在另一个表中更新

时间:2011-08-26 10:54:22

标签: asp.net-mvc-3 entity-framework-4

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

public partial class Product
    {
        [Key]
        public int ProductID { get; set; }
        public string Name { get; set; }
        <remaining fields>
        public virtual ProductStock ProductStock { get; set; }
}

public partial class ProductStock
    {
        [Key, Column(Order = 0)]
        [ForeignKey("Product")]
        public int ProductID { get; set; }
        public decimal QuantityOnHand { get; set; }
        public Nullable<decimal> QuantitySold { get; set; }
        public Nullable<decimal> QuantityOnOrder { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual Product Product { get; set; }
    }
public partial class PurchaseOrderHeader
    {
        public PurchaseOrderHeader()
        {
            this.PurchaseOrderDetails = new HashSet<PurchaseOrderDetail>();
        }
        [Key, Column(Order = 0)]
        public int PurchaseOrderID { get; set; }
        public System.DateTime OrderDate { get; set; }
        public decimal SubTotal { get; set; }
        public decimal TaxAmt { get; set; }
        public decimal Freight { get; set; }
        public decimal TotalDue { get; set; }
        public virtual ICollection<PurchaseOrderDetail> PurchaseOrderDetails { get; set; }
}

public partial class PurchaseOrderDetail
    {
        public int PurchaseOrderID { get; set; }
        public int PurchaseOrderDetailID { get; set; }
        public decimal OrderQty { get; set; }
        public int ProductID { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal LineTotal { get; set; }

        public virtual PurchaseOrderHeader PurchaseOrderHeader { get; set; }
        public virtual Product Product { get; set; }
    }

现在要求是我们创建采购订单时,它会将数据插入到PurchaseOrderHeader表和PurchaseOrderDetail表中(没问题)。现在我们必须更新QuantityOnOrder字段的ProductStock表(附加OrderQty)。

  1. 我们如何更新?
  2. 我们是否已为PurchaseOrderHeader实体创建事务并为ProductStock实体创建另一个插入操作并提交事务?
  3. 我们使用存储过程吗?
  4. 或者我们可以用更好的方法来实现这个目标吗?
  5. 任何人都可以建议解决方案吗?

1 个答案:

答案 0 :(得分:2)

如果您在调用SaveChanges()之前对上下文进行了所有更改,则EF实际上会为您创建一个事务。因此,这里的过程如下:

  1. 创建(或获取)您的上下文
  2. 插入
  3. 选择您需要更新的项目,然后更改其中的值。 (此更新与任何其他更新完全相同。下面提供了示例。)
  4. 在上下文中调用SaveChanges()
  5. 至于如何实际进行更新,您需要做的是选择要更新的内容。那么,这个特定产品的ProductStock条目。然后,您只需更改该值。像tihs:

    var stock  = (from p in context where p.ProductId == the_product_id select p).First();
    stock.QuantityOnOrder = new_value;
    

    希望有所帮助。 :)