如何在没有先加载实体框架模型的情况下从Entity Framework模型中删除对象? [英] How do I delete an object from an Entity Framework model without first loading it?
问题描述
在实体框架中,删除数据对象的唯一方法似乎是
MyEntityModel ent = new MyEntityModel();
ent.DeleteObject(theObjectToDelete);
ent.SaveChanges();
但是,这种方法需要将对象加载到这种情况下,删除它。有没有办法删除只引用其ID的业务对象?
如果使用Linq或Lambda表达式更聪明,那也是很好的。主要目标是避免加载数据,以便删除它。
值得一提的是,实体框架支持两者都是Linq to Entities和Entity SQL。如果您发现自己想要执行可能影响许多记录的删除或更新,您可以使用相当于 ExecuteNonQuery
的更改。
在实体SQL中,这可能看起来像
HelloEfEntities
Dim qStr =Delete& _
FROM Employee
db.ExecuteStoreCommand(qStr)
db.SaveChanges()
结束使用
在这个例子中, db
是我的 ObjectContext
。另请注意, ExecuteStoreCommand
函数接受可选的参数数组。
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();
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?
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.
It is worth knowing that the Entity 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
In this example, db
is my ObjectContext
. Also note that the ExecuteStoreCommand
function takes an optional array of parameters.
这篇关于如何在没有先加载实体框架模型的情况下从Entity Framework模型中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!