我有一个产品类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
public virtual Brand Brand { get; set; }
}
我正在尝试更新模型:
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
product.Brand = db.Brands.Find(product.Brand.Id);
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
问题是我所有的属性都更新了,但是品牌!我该怎么做才能更新它?
如果我做:
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
db.Products.Attach(product);
product.Brand = db
.Brands
.Find(2); // << with a static value
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
它有效......但如果我在下面尝试这个,即使 BrandId 是 2,它也不起作用:
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
db.Products.Attach(product);
int BrandId = product.Brand.Id;
product.Brand = db
.Brands
.Find(BrandId);
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}