我们正在为正在进行的项目使用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)。
任何人都可以建议解决方案吗?
答案 0 :(得分:2)
如果您在调用SaveChanges()
之前对上下文进行了所有更改,则EF实际上会为您创建一个事务。因此,这里的过程如下:
SaveChanges()
。至于如何实际进行更新,您需要做的是选择要更新的内容。那么,这个特定产品的ProductStock条目。然后,您只需更改该值。像tihs:
var stock = (from p in context where p.ProductId == the_product_id select p).First();
stock.QuantityOnOrder = new_value;
希望有所帮助。 :)