We are using ASP.NET MVC 3 and Entity Framework for our ongoing project. Our entity models are (I have given the important fields only)
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; }
}
Now the requirement is when we create the purchase order it will insert data to PurchaseOrderHeader table and PurchaseOrderDetail table (No problem w开发者_如何学Pythonith this). Now we have to update the ProductStock table for QuantityOnOrder field (append the OrderQty).
- How can we update this?
- Do we have create a transaction and create a separate insert operation for PurchaseOrderHeader entity and another for ProductStock entity and commit the transaction ?
- Do we use stored procedure?
- Or we can use any better way to achieve this?
Can any one suggest solutions?
If you do all your changes to your context before calling SaveChanges()
, EF actually creates a transaction for you. Thus the process here goes like this:
- Create (or get) your Context
- Do your inserts
- Select the item you need to update, then change the value on it. (This update is the same as any other update, really. Example provided below.)
- Call
SaveChanges()
on the context.
As for how to actually do the update, what you need to do is select the thing you want to update. So, the ProductStock entry for this specific product. You then simply change the value. Something like tihs:
var stock = (from p in context where p.ProductId == the_product_id select p).First();
stock.QuantityOnOrder = new_value;
Hope that helps. :)
精彩评论