我如何删除不先加载它的实体框架模型中的对象? [英] How do I delete an object from an Entity Framework model without first loading it?

查看:102
本文介绍了我如何删除不先加载它的实体框架模型中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定我已经看到了这个问题的答案的地方,但我不能与SO或一对夫妇的搜索找到谷歌,请问它再反正...

I am quite sure I've seen the answer to this question somewhere, but as I couldn't find it with a couple of searches on SO or google, I ask it again anyway...

在实体框架,删除数据对象的唯一方法似乎是

In Entity Framework, the only way to delete a data object seems to be

MyEntityModel ent = new MyEntityModel();
ent.DeleteObject(theObjectToDelete);
ent.SaveChanges();

然而,这种方法需要被装载到,在这种情况下,控制器首先,只是将其删除该对象。有没有一种方法来删除一个业务对象只引用比如说它的ID?

However, this approach requires the object to be loaded to, in this case, the Controller first, just to delete it. Is there a way to delete a business object referencing only for instance its ID?

如果有使用LINQ或lambda前pressions一个聪明的办法,那就是没关系。其主要目标,不过,是为了避免装载数据只是将其删除。

If there is a smarter way using Linq or Lambda expressions, that is fine too. The main objective, though, is to avoid loading data just to delete it.

推荐答案

值得明知Entiy框架支持为LINQ到实体和实体SQL。如果你发现自己想要做删除或更新了可能会影响多条记录,您可以使用的ExecuteNonQuery 的等价物。在实体SQL,这可能看起来像

It is worth knowing that the Entiy Framework supports both to Linq to Entities and Entity SQL. If you find yourself wanting to do deletes or updates that could potentially affect many records you can use the equivalent of ExecuteNonQuery. In entity SQL this might look like

   Using db As New HelloEfEntities

        Dim qStr = "Delete " & _
                  "FROM Employee"
        db.ExecuteStoreCommand(qStr)
        db.SaveChanges()
    End Using

在这个例子中,db是我的ObjectContext。还要注意的是 ExecuteStoreCommand 函数接受一个参数数组(可选)。

In this example, db is my ObjectContext. Also note that the ExecuteStoreCommand function takes an optional array of parameters.

这篇关于我如何删除不先加载它的实体框架模型中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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