views:

417

answers:

1

I have following structure of the database

CREATE TABLE IF NOT EXISTS `klienci` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nazwa` varchar(50) NOT NULL,
  `miejscowosc` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `klienci_do_trasy` (
  `klient_id` int(11) NOT NULL,
  `trasa_id` int(11) NOT NULL,
  `seq` int(11) NOT NULL,
  PRIMARY KEY (`klient_id`,`trasa_id`),
  KEY `trasa_id` (`trasa_id`),
  KEY `klient_id` (`klient_id`,`trasa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `trasy` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nazwa` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

ALTER TABLE `klienci_do_trasy`
  ADD CONSTRAINT `klienci_do_trasy_ibfk_5` FOREIGN KEY (`klient_id`) REFERENCES `klienci` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `klienci_do_trasy_ibfk_6` FOREIGN KEY (`trasa_id`) REFERENCES `trasy` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

And I would like to run query similar to:

DELETE FROM klienci_do_trasy WHERE klient_id = 1;

Don't know how to do this with ADO.NET entity

+2  A: 

With EntityFramework v1.0 there is no such a possibility. You would have to call ObjectContext.DeleteObject for each entity:

 using (TheDataContext entities = new TheDataContext())
  {
        List<Klienci_do_tracy> kdcList = //get entities to delete
        foreach(Klienci_do_tracy kdc in kdcList)
        {
             entities.DeleteObject(kdc);
        }
        entities.SaveChanges();
  }

or you could use EntityCommand to do that on old fashion way.

[update: run native sql with EF]

var eConnection = (System.Data.EntityClient.EntityConnection)yourContextInstance.Connection;

DbConnection conn = eConnection.StoreConnection;

 if (conn.State != ConnectionState.Open)
      conn.Open();  
 using (DbCommand cmd = conn.CreateCommand())
       {
        //write native sql query
        cmd.CommandText = "delete from...where...";
        cmd.ExecuteNonQuery();
       }

You would probably have to wrap this in try finally to ensure closing connection if something goes wrong and additional checks on connestion state.

Misha N.
How to do that if my context is: korlenEntities2 _db = new korlenEntities2(); System.Data.EntityClient.EntityCommand com = new System.Data.EntityClient.EntityCommand(); com.Connection = new System.Data.EntityClient.EntityConnection("name=korlenEntities2"); com.Connection.Open(); com.CommandText = "DELETE VALUE FROM klienci_do_trasy"; com.CommandType = System.Data.CommandType.Text; com.ExecuteNonQuery();does not work and require manual opening connection :(
Inez
Sorry Inez, I mislead you when saying to use EntityCommand. Look updated answer to see how to run native query with ef.
Misha N.

related questions