我有以下数据库结构
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;
我想运行类似的查询:
DELETE FROM klienci_do_trasy WHERE klient_id = 1;
不知道如何使用ADO.NET实体
执行此操作答案 0 :(得分:4)
使用EntityFramework v1.0,没有这种可能性。您必须为每个实体调用ObjectContext.DeleteObject:
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();
}
或者您可以使用EntityCommand以旧时尚的方式做到这一点。
[更新:使用EF运行本机sql]
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();
}
您可能必须将此包装在最后尝试以确保在出现问题时关闭连接以及对连接状态的其他检查。