简体   繁体   中英

Error while deleting record in a table with two databases

First I want to report that because of my English this is a machine translation from Spanish to English, Please excuse for mistakes that may have been in the translation.

I have a problem in a small program I'm doing and I would like you could help me: I have a database with two tables customer (pelo2 hair), I access them in two different windows at first had a delete button in the first window, to remove all the selected customer record, but having the other window all customer data window and change it gives me the following error:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[Peluqueria.Pelos2]' to type 'Peluqueria.Pelos2'.

this occasionally happen in the event of the button Eliminar

        private void Eliminar_Click(object sender, RoutedEventArgs e)
    {
        MessageBoxResult result = MessageBox.Show("Seguro que quieres eliminar este cliente?", "Confirmar",
        MessageBoxButton.YesNo, MessageBoxImage.Information);
        if (result == MessageBoxResult.Yes)
        {
            Pelo guar = (Pelo)Application.Current.Properties["seleccionar"];


                var verTrabajo = (from o in baseDeDatos.Pelos2s
                                  where o.num == guar.num
                                  select o);


                baseDeDatos.Pelos2s.DeleteOnSubmit((Pelos2)verTrabajo);
                baseDeDatos.SubmitChanges();
                actualizarDatos();

        }
    }          

specifically in the row:

baseDeDatos.Pelos2s.DeleteOnSubmit((Pelos2)verTrabajo);

I must say that I get the same error, even with the baseDeDatos.Pelos. Can I help you can know what I'm doing wrong? Can it be done differently? Thanks for your help.

This line:

var verTrabajo = (from o in baseDeDatos.Pelos2s
                                  where o.num == guar.num
                                  select o);

returns a collection. It may well be that the collection contains just the one record you're expecting to delete but you need to be specific.

If you're expecting it to return one result so you can use that result to delete try using SingleOrDefault() :

var verTrabajo = (from o in baseDeDatos.Pelos2s
                                  where o.num == guar.num
                                  select o).SingleOrDefault();

Make sure you check if it's not null before you use it for the delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM