簡體   English   中英

實體框架6將帶有外鍵的數據插入到Azure SQL數據庫中

[英]Entity Framework 6 Insert data with foreign keys into azure sql database

我在azure上有一個sql數據庫,可以加載類似文章的數據。 如果我嘗試按表順序保存數據,則billingDetails會在整個保存過程中正常運行它的位置,並且沒有任何異常,但是如果我之后在Visual Studio IDE中顯示表的數據,則不會顯示任何新條目。

我的表格訂單,頭寸和billingDetails的流利API看起來像這樣:

//------Relationship Orders <--> Billing Details-------
//Configure the primary key for orders (Primary key BillingDeatailID is foreign key in orders)
modelBuilder.Entity<Orders>()
.HasKey(b => b.BillingDetailID);

//one-to-one relationship 
modelBuilder.Entity<BillingDetails>()
.HasRequired(b => b.Order)
.WithRequiredPrincipal(b => b.BillingDetails)
.WillCascadeOnDelete(false);

//------Relationship Products <--> Positions-------
//one-to-many relationship (a position can have one product but a product can have many positions (optional relationship); the table positions contains ProductID as a required foreign key if the relation exists)
modelBuilder.Entity<Positions>()
.HasOptional<Products>(p => p.Product)
.WithMany(p => p.Positions)
.HasForeignKey(p => p.ProductID);


//------Relationship Orders <--> Positions-------
//one-to-many relationship (a position can have one order but an order can have many positions (optional relationship); the table positions contains OrderID as a required foreign key if the relation exists)
modelBuilder.Entity<Positions>()
.HasOptional<Orders>(o => o.Order)
.WithMany(o => o.Positions)
.HasForeignKey(o => o.OrderID);

我的數據保存操作:

public ActionResult CompleteOrder() 
        {
            //save data to database
            using (var context = new OnlineShopContext())
            {
                BillingDetails billDetails = new BillingDetails();
                Orders order = new Orders();

                try
                {
                    //save billing details
                    try
                    {
                        billDetails.Owner = Session["PaymentOwner"].ToString();
                        billDetails.CardType = (int)Session["PaymentType"];
                        if(Session["PaymentType"].ToString() == "0"){
                            billDetails.Number = Session["PaymentCreditcardNumber"].ToString();
                        }else{
                            billDetails.Number = Session["PaymentAccountNumber"].ToString();
                        }

                        billDetails.ExpiryMonth = (int)Session["PaymentExpireMonth"];
                        billDetails.ExpiryYear = (int)Session["PaymentExpireYear"];
                        billDetails.Swift = Session["PaymentSwift"].ToString();
                        billDetails.Blz = Session["PaymentBlz"].ToString();
                        billDetails.IBAN = Session["PaymentIBAN"].ToString();

                        context.BillingDetails.AddOrUpdate(billDetails);
                        context.Entry(billDetails).State = EntityState.Added;

                        if (context.SaveChanges() > 0)
                        {
                            //saved
                        }
                        else
                        {
                            string Msg = "Error while saving!";

                            return View((object)Msg);
                        }
                    }
                    catch (OptimisticConcurrencyException ocEx)
                    {
                        log.Fatal("OptimisticConcurrencyException while saving billing details: " + ocEx.Message);
                        string Msg = "Error while saving!";

                        return View((object)Msg);
                    }

                    //get the id of added billing details item and complete the order
                    var billingDetailsId = billDetails.BillingDetailID;

                    order.BillingDetailID = billingDetailsId;

                    order.DeliveryName = Session["DeliveryName"].ToString();
                    order.DeliveryStreet = Session["DeliveryStreet"].ToString();
                    order.DeliveryCity = Session["DeliveryCity"].ToString();
                    order.DeliveryZipCode = Session["DeliveryZipCode"].ToString();
                    order.DeliveryCountry = Session["DeliveryCountry"].ToString();

                    order.BillName = Session["BillName"].ToString();
                    order.BillStreet = Session["BillStreet"].ToString();
                    order.BillCity = Session["BillCity"].ToString();
                    order.BillZipCode = Session["BillZipCode"].ToString();
                    order.BillCountry = Session["BillCountry"].ToString();

                    order.OrderDate = DateTime.Now;

                    //save the order
                    try
                    {
                        context.Orders.AddOrUpdate(order);
                        context.Entry(order).State = EntityState.Added;
                        if(context.SaveChanges() > 0){
                            //saved
                        }
                        else{
                            string Msg = "Error while saving!";

                            return View((object)Msg);
                        }
                    }
                    catch (OptimisticConcurrencyException ocEx)
                    {
                        log.Fatal("OptimisticConcurrencyException while saving order: " + ocEx.Message);
                        string Msg = "Error while saving!";

                        return View((object)Msg);
                    }

                    //get id of added order
                    var orderId = order.OrderID;

                    //save all positions of this order
                    foreach (var item in CartItems)
                    {
                        Positions position = new Positions();
                        position.OrderID = orderId;
                        position.ProductID = item.product.ProductID;
                        position.Amount = item.amount;

                        try
                        {
                            context.Positions.AddOrUpdate(position);
                            context.Entry(position).State = EntityState.Added;

                            if(context.SaveChanges() > 0){
                               //saved
                            }
                            else{
                               string Msg = "Error while saving!";

                                return View((object)Msg);
                            }
                        }
                        catch (OptimisticConcurrencyException ocEx)
                        {
                            log.Fatal("OptimisticConcurrencyException while saving position: " + ocEx.Message);
                            string Msg = "Error while saving!";

                            return View((object)Msg);
                        }
                    }

                }
                catch (Exception ex)
                {
                    log.Fatal("Error while saving order data. Exception: " + ex.Message);

                    string Msg = "Error while saving!";

                    return View((object)Msg);
                }

                //empty the shopping cart
                RemoveAllCartItems();

                //redirect to the catalog
                return RedirectToAction("Index", "Products");
            }
        }

當我在調試時檢查它們時,ID正確地增加了(例如ID 9),並且如果我再復制一次,則ID再次增加了(例如ID 10)。

數據庫中已經有一些虛擬數據,並且它們不會更改,因此也不會意外更新它們。

如果嘗試在IDE中顯示新添加的數據,為什么不顯示它們?

在這種情況下,需要檢查的第一件事是要從同一數據庫讀取數據並將數據寫入同一數據庫。

我在您的代碼中注意到的另一件事是:

        context.BillingDetails.AddOrUpdate(billDetails);
        context.Entry(billDetails).State = EntityState.Added;

為什么需要設置實體狀態?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM