Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

asp.net mvc - How do I delete an object from an Entity Framework model without first loading it?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...