LINQ到实体删除 [英] Linq to Entities delete

查看:251
本文介绍了LINQ到实体删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个内置的方式来删除与LINQ到entites的,使用主键。

Is there a built in way to delete with Linq to Entites, using the Primary Key.

目前M编辑解决方法是创建一个名为DeleteTable一个存储过程(表作为表名)

Currently m work around is to create a Stored Procedure called DeleteTable (table being the table name)

,然后在C#LINQ到实体我只是做context.DeleteTable(ID)

and then in C# LINQ To Entities I just do context.DeleteTable(ID)

这是最好的办法吗?还有什么其他的选择呢?

Is this the best way? What other options are there?

推荐答案

如果你不想去数据库检索对象的所有领域,你可以创建类的新实例,将其附加到一个新的上下文,删除,并保存更改。这让EF生成相应的删除命令。

If you don't want to go to the database to retrieve all of the object's fields, you can create a new instance of the class, attach it to a new context, remove that, and save the changes. This lets EF generate the appropriate delete command.

using (var context = new MyContext())
{
  var myObject = new MyObject { ID = 3 };
  context.MyObjectSet.Attach(myObject);
  context.MyObjectSet.DeleteObject(myObject);
  context.SaveChanges();
}

请注意:这会扔你想删除的对象异常不存在。 。如果您是确保对象存在只是适当

Note: this will throw an exception of you're trying to delete an object which does not exist. That's only appropriate if you're sure the object exists.

注2:这是假定您已经设置了您的实体,以便生成的delete命令没有引用任何其他领域比该ID(即没有timestamp的属性,或任何类似的,将被列入查询)

Note 2: this assumes you've set up your entities so that the generated delete command references no other fields than the ID (meaning no Timestamp properties, or anything similar that would be included in the query)

这篇关于LINQ到实体删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆