我基本上对以下课程有疑问:ShoppingBasket和Coupon。 我的ShoppingBasket模型具有以下属性:
public Coupon[] theCoupons = new Coupon[20];
public string userForeignKey {get;set;} //To identify which user the basket belongs to
public int iCurrentCoupon {get;set;} //Where I am in the coupon-array
优惠券控制器addToShoppingBasket-Method看起来像:
public ActionResult addToShoppingBasket(int id) //Coupon id
{
// Get current user
var store = new UserStore<ApplicationUser>(db);
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindById(User.Identity.GetUserId());
// Get coupon with selected id
Coupon tmpCoupon = db.Coupons.SingleOrDefault(x => x.id == id);
// Get ShoppingBasket of current user
var tmpBasket = db.ShoppingBaskets.SingleOrDefault(x => x.userForeignKey == currentUser.Id);
// add the coupon into basket; here's the problem I think
tmpBasket.theCoupons[tmpBasket.iCurrentCoupon] = tmpCoupon;
//there's an if-clause and some other stuff around this, basically not to overwrite already added coupons
tmpBasket.iCurrentCoupon++;
db.SaveChanges();
return RedirectToAction("Index", "ShoppingBasket");
}
ShoppingBasket-Controller的索引方法:
public ActionResult Index()
{
//Get current user
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
//Get shopping basket from selected user
var basketConsumer = db.ShoppingBaskets.Where(i => i.userForeignKey == currentUser.Id).SingleOrDefault();
return View(basketConsumer);
}
在运行程序的同时检查basketConsumer时,我可以看到iCurrentCoupon
已正确更新,但是basketConsumer.theCoupons[basketConsumer.iCurrentCoupon]
仍然(或再次是?)为null,并且在那里所做的更改未保存。
我尝试过类似的事情:
db.ShoppingBaskets.Attach(tmpBasket);
db.Entry(tmpBasket).State = EntityState.Modified;
db.Coupons.Attach(tmpBasket.theCoupons[tmpBasket.iCurrentCoupon];
我不得不翻译大多数内容,因此代码中可能存在细微的不一致之处。我已经很长时间没有使用过asp.net或C#了,但这似乎是一件微不足道的事情,我一生都无法解决。为什么iCurrentCoupon
被保存但数组未保存(以及如何更改它)?
任何帮助深表感谢!
编辑:不确定是什么问题,但是我通过使theCoupons[]
成为ICollection而不是数组来解决了问题。之后,我更新了两个类,以使它们具有多对多关系,如here所示。删除不再需要的内容,添加迁移,更新数据库,然后它就可以工作了。
我将继续公开这个问题,也许有人可以告诉我为什么我的第一次尝试没有奏效。