導覽屬性Navigate property之研究
- Product VS ProductCategory 為1對1
- //以下指令會新增Product與ProductCategory
db.Products.Add(new Product() { Name = "文具" + "類別下的商品1", Color = Color.Red, Description = "N/A", Price = 99, PublishOn = DateTime.Now,
ProductCategory = new ProductCategory() { Id = 1, Name = "文具" } });
- 如果Product裡的ProductCategory屬性不新增的話,應該可以變成只新增Product
A:是不行的,因為Product對ProductCategory是一對一關係,
所以當實現Prouduct時也必須實現ProuductCategory;
反之ProductCategory對Prouduct是ㄧ對多關係,
實現ProuductCategory時Prouduct可為Null。
另外OrderHeader對OrderDetail也是ㄧ對多關係。
- 新增類別以下導覽屬性有Key就不新增,沒有對應的Key就新增一筆
using eComerce.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
namespace eComerce.Controllers
{
//[Authorize] // 必須登入會員才能使用訂單結帳功能
public class OrderController : BaseController
{
// 顯示完成訂單的表單頁面
public ActionResult Complete()
{
return View();
}
// 將訂單資料與購物車資料寫入資料庫
[HttpPost]
public ActionResult Complete(OrderHeader form)
{
MyDbContext db = new MyDbContext();
//db.ProductCategories.Add(new ProductCategory() { Id = 1, Name = "文具" });
//db.SaveChanges();
//以下指令會新增Product與ProductCategory
db.Products.Add(new Product() { Id = 1, Name = "文具" + "類別下的商品1", Color = Color.Red, Description = "N/A", Price = 99, PublishOn = DateTime.Now, ProductCategory = new ProductCategory() { Id = 1, Name = "文具" } });
db.SaveChanges();
//手動建立購物車測試資料
Product Product2 = new Product() { Id = 2, Name = "文具" + "類別下的商品1", Color = Color.Red, Description = "N/A", Price = 99, PublishOn = DateTime.Now, ProductCategory = new ProductCategory() { Id = 2, Name = "文具" } };
Cart Cart = new Cart() { Product = Product2, Amount = 123 };
this.Carts.Add(Cart);
// 將訂單資料與購物車資料寫入資料庫
OrderHeader oh = new OrderHeader()
{
//Member = member,
ContactName = form.ContactName,
ContactAddress = form.ContactAddress,
ContactPhoneNo = form.ContactPhoneNo,
BuyOn = DateTime.Now,
Memo = form.Memo,
OrderDetailItems = new List<orderdetail>()
};
int total_price = 0;
foreach (var item in this.Carts)
{
total_price += item.Product.Price * item.Amount;
oh.OrderDetailItems.Add(new OrderDetail() { Product = Product2, Price = Product2.Price, Amount = item.Amount });
}
oh.TotalPrice = total_price;
db.Orders.Add(oh);
db.SaveChanges();
// 訂單完成後必須清空現有購物車資料
this.Carts.Clear();
// 訂單完成後回到網站首頁
return RedirectToAction("Complete", "Order");
}
}
}