ontehfritz – Application Development and Stuff

November 25, 2008

.Net Entity Framework Deleting Objects in N-Tier Environment

Filed under: .Net Entity Framework 3.5 SP1 — ontehfritz @ 12:46 pm

Well, here I am again, This has turned into a mini series. Please see Adding Objects and Updating Objects for the other episodes of fun!

Deleting objects in an N-Tier environment has been a pleasure and worked as expected. Here we go!

WCF Methods:

/*Private method so I do not have to duplicate these lines everytime*/
  private void Delete(EntityObject o)
    {
        using(CorporateEntities ce = new CorporateEntities())
        {
            ce.Attach(o);
            ce.DeleteObject(o);
            ce.SaveChanges();
        }
    }

/*The exposed method to delete a Store from the database*/

    public void RemoveStore(Stores removeStore)
    {
        this.Delete(removeStore);
    }

Nice eh ..? finally something simple and meaningful.

Now for the client code:

 client.RemoveStore(client.GetStoreByID(666)); /*WCF Method to retrieve the store I want to delete*/

That is it!!! Not much left to say on deleting. We now have completed this mini series on Adding, Updating and Deleting Objects in N-Tier environment using the entity framework. I will post updates on the posts made when I find better ways to do these operations, but for now this is what works.

Hopes this helps people and avoids the struggles I had. Please post links to better solutions and/or in the comments.

Stay Cool ;)

Note and Disclaimer: This is test code and may contain bugs and/or improper error handling, it is for academic purposes only, for sharing knowledge, and collaboratively coming up with better solutions. Please always practice proper security, error handling, and coding best practices in production. I am not liable for any code used here; use @ your own risk. Have fun and share the experience and knowledge. Remember, no question is a stupid question, and failure gives us insight.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.