لدي فئة على النحو التالي:
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; }
}
تستخدم طريقة GET لـ CategoryController هذه الفئة Estanting Consust وإضافة جميع المنتجات إلى كائن CatevoryViewModel هذا. ثم يتكرر من خلال جميع المنتجات وتعيين خاصية المنتجات المحددة إلى 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);
}
باستخدام Debugger ، ألاحظ أن Foreach ينفذ ، ولكن لا يزال لدى CatevoryView جميع المنتجات التي تحتوي على خاصية محددة على خطأ.
ومع ذلك ، هذا واحد يعمل بشكل جيد:
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 ويتم تخزين المنتجات والفئات في قاعدة البيانات مع وجود العديد من العلاقة.