实体框架6将带有外键的数据插入到azure sql数据库中

时间:2015-06-29 06:08:13

标签: c# sql-server entity-framework

我在azure上有一个sql数据库,可以像文章一样加载数据。如果我尝试在表格中保存数据,billingDetails和position它正在保存过程中运行,没有任何例外,但如果我之后在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中显示我的新添加数据,为什么不显示?

1 个答案:

答案 0 :(得分:0)

在这种情况下,您需要检查的第一件事是您正在从同一数据库读取数据并将数据写入同一数据库。

我在你的代码中注意到的另一件事是:

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

为什么需要设置实体状态?