Entity Framework Query Examples

1. February 2010 21:24

Well I've finally have gotten into the Entity Framework in ASP.NET 3.5 Service Pack 1.  I was playing around with it and wanted to post how to do some basic queries with LINQ to Entities. I had a hard time just finding basic information on querying data from the model.  There are a lot of posts, but I just wanted something straight to the point and nothing else. The code in this post does your basic CRUD operations (Create, Read, Update and Delete).  I actually used the Classified Starter Kit as the database for creating my entity model.

Note: Here is what I followed for creating an entity model. I chose to only create using the Tables in the database.

http://msdn.microsoft.com/en-us/library/cc716703.aspx

Here is a screenshot of the model created in Visual Studio.



What I did was make a class to complete CRUD operations on the Categories table in the database.  I have a class named Category with methods as needed to accomplish this. I also used lambda expressions in my queries.  

Below I will outline the methods for the following:

Get()
GetByID(int id)
GetByName(string name)
Add(string name)
Update(int id, string newName)
Delete(int id)

 

Class Outline

The variable testDBContext is what allows us to access the entity model so we can run queries and interact with it. The object TestDBEntities was created during the creation of the Entity Model

Get Method

Get By ID Method

Get By Name Method

Add Method

Update Method

Delete Method

Also here is some quick debug code if you would like to put in your code behind of your ASPX page.

Well I hope this will get you started like it did for me. I look forward to working more with the framework and getting into more complex queries.

As usual with me, I'm a concept driven developer so I need to understand the concept of something and I explore from there.

Tags:

ASP.NET




My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

http://ocwconsortium.org/

John On Twitter

Discounts