我有一个 CategoryViewModel 如下:
public class CategoryViewModel
{
public string Id {get; set;}
public string Name { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public List<string> SelectedProductIds { get; set; }
}
CategoryController 的 GET 方法使用此 CategoryViewModel 实例化一个对象并将所有 Products 添加到此 CategoryViewModel 对象。然后它遍历所有产品并将产品的 Selected 属性设置为 True ,它们包含在类别对象中:
public ActionResult CategoryController(string categoryId)
{
CategoryDbContext db = new CategoryDbContext();
CategoryRepository CategoryRepo = new CategoryRepository(db);
ProductRepository ProductRepo = new ProductRepository(db);
Category category = CategoryRepo.GetCategory(categoryId);
CategoryViewModel categoryView = new CategoryViewModel()
{
Id = category.Id,
Name = category.Name,
Products = from product in ProductRepo.GetAllProducts()
select new SelectListItem { Text = product.Name, Value = product.Id, Selected = false}
};
foreach (var product in category.Products)
{
categoryView.Products.Where(x => x.Value == product.Id).FirstOrDefault().Selected = true;
}
return View(categoryView);
}
使用调试器,我观察到 foreach 执行,但 categoryView 的所有具有 Selected 属性的产品仍设置为 False。
但是,这个工作正常:
public ActionResult CategoryController(string categoryId)
{
CategoryDbContext db = new CategoryDbContext();
CategoryRepository CategoryRepo = new CategoryRepository(db);
ProductRepository ProductRepo = new ProductRepository(db);
Category category = CategoryRepo.GetCategory(categoryId);
CategoryViewModel categoryView = new CategoryViewModel()
{
Id = category.Id,
Name = category.Name,
Products = from product in ProductRepo.GetAllProducts()
select new SelectListItem { Text = product.Name, Value = product.Id, Selected = category.Products.Contains(product)}
};
return View(categoryView);
}
有人可以解释一下区别以及为什么第一个不起作用吗?
编辑: 我使用的是 EF 6,产品和类别以多对多关系存储在数据库中。