LINQ到实体删除

编程入门 行业动态 更新时间:2024-10-25 14:25:38
本文介绍了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到实体删除

本文发布于:2023-06-03 10:03:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!