I'm trying to delete a selected row in my datagrid as well as that same row in my database.
I'm getting an error though where dbset does not contain a definition for SaveChanges
.
Relatively new to Linq and EF. Anyone know where this might be coming from?
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
using (EFContext db = new EFContext())
{
int proId = (ProductDatagrid.SelectedItem as Product).ProductID;
Result result = (from r in db.products where r.ProductID == proId select r).SingleOrDefault();
db.Product.Remove(result);
db.Product.SaveChanges();
ProductDatagrid.ItemsSource = db.Results.ToList();
}
}
You can remove .Product
from the Remove()
and SaveChanges()
methods. The Result result
will be tracked by Entity Framework so it will know which table to remove your record
from and then you can call db.SaveChanges()
without any errors since it is being called on the DbContext (EfContext
):
using (EFContext db = new EFContext())
{
int proId = (ProductDatagrid.SelectedItem as Product).ProductID;
Result result = (from r in db.products where r.ProductID == proId select r).SingleOrDefault();
// .Product removed
db.Remove(result);
db.SaveChanges();
ProductDatagrid.ItemsSource = db.Results.ToList();
}
But if you want to continue with the syntax of using db.Product
, then you can also attach the Result
object to the dbContext without the query like this:
using (EFContext db = new EFContext())
{
int proId = (ProductDatagrid.SelectedItem as Product).ProductID;
Result result = new Result { ProductId = proId};
db.Product.Attach(result);
db.Product.Remove(result);
db.Product.SaveChanges();
ProductDatagrid.ItemsSource = db.Results.ToList();
}
Or you can set the entity state to deleted and remove it that way:
using (EFContext db = new EFContext())
{
int proId = (ProductDatagrid.SelectedItem as Product).ProductID;
Result result = new Result { ProdId = proId };
db.Entry(result).State = EntityState.Deleted;
db.SaveChanges();
ProductDatagrid.ItemsSource = db.Results.ToList();
}