0

I've successfully selected the Objects I want to delete. But the problem is when I remove an item from Object array, it doesn't make any changes. My code is following below..

My database

public List<Product> db = new ProductRepository().GetProducts();

Here it shows all the products with checkbox..

public ActionResult MultipleDeletes()
        {
            return View(db);
        }

On Submitting "Button named Delete", I got problem.

[HttpPost]
        public ActionResult MultipleDeletes(int[] selectedProducts)
        {  
            var del_products  = from x in selectedProducts
                           from y in db
                           where y.ProductId == x
                           select y;

            foreach (var item in del_products)
            {
                //Product p = db.Find(item.ProductId);
                //db.Remove(p);
                //db.SaveChanges();
            }                    

            return View(db);
        }

Could anyone help me? can you also tell me, how to write Lambda expression instead of LinQ?

undefined
  • 33,537
  • 22
  • 129
  • 198
kk-dev11
  • 2,654
  • 5
  • 37
  • 48
  • 1
    This question isnt actually about MVC its about your ERM framework. Which database access technology are you using? – undefined Jan 06 '12 at 08:18
  • Thats your actual database file, how are you accessing the database? are you using entity framework or linq to SQL or some other ORM? – undefined Jan 06 '12 at 08:42
  • I'm using Entity Framework (Model First).. I've got 2 model. Product Model, it's the attributes. and ProductRepository creates products using NBuilder. – kk-dev11 Jan 06 '12 at 08:46

2 Answers2

0

I think in this case you need to make use of Delete rather than remove.

Use following and see if it works

db.DeleteObject(p)
db.SaveChanges()
Pankaj Upadhyay
  • 12,966
  • 24
  • 73
  • 104
  • I already have from in the previous line. Product p = db.Find(item.ProductId).. it say that find has some invalid arguments. And then .DeleteObject doesn't appear in Intellisense. – kk-dev11 Jan 06 '12 at 08:33
0

The problem was in the model. I used NBuilder.. so it didn't really save the data. I built an DbContext. Then it worked. Solution is ..

public ProductDBContext db = new ProductDBContext();


        [HttpPost]
        public ActionResult MultipleDeletes(int[] selectedProducts)
        {
            foreach (int item in selectedProducts)
            {
               Product product = db.Where(p => p.ProductId == item).SingleOrDefault();
               db.Remove(product);
               db.SaveChanges();
            }
          return View();
        }
kk-dev11
  • 2,654
  • 5
  • 37
  • 48