Archive

Archive for the ‘ADO.NET Entity Data Model’ Category

Using LINQ to ADO.NET Entity Data Model

December 25, 2010 2 comments

Hi All,

try this Example to use Using LINQ to ADO.NET Entity Data Model and we will learn how to insert and update and delete and Get data from Database

In this Example i’m using Northwind Database .. you can also get it from  here

1) Open VS 2008 or VS2010 and create a new WebSite and right click on solution and select add new item then Add a new ADO.NET Data Model

Using the ADO.NET Entity Framework wizard you can easily create a representation of the sample Northwind database like the one below:

Now We are going to the following :-

Query an Entity from the Database

NorthwindEntities dbContext = new NorthwindEntities();
var query = from p in dbContext.ProductSet
           where p.Categories.CategoryName == "Seafood"
           select p;
IEnumerable<Product> products = query.ToList();

Update an Entity in the Database :-

NorthwindEntities dbContext = new NorthwindEntities();
Product product = dbContext.ProductSet.Single( p => p.ProductName == "Aniseed Syrup" );
product.UnitPrice = 1000;
dbContext.SaveChanges();

the above code using to select single Product object from the database, update its price, and then save the changes back to the database.

Insert a New Record(s) in the Database :-

The code below shows you how to create a new Category object. Then how to create two new Products and associate them with the Category. Finally, all three objects are saved in the database

NorthwindEntities dbContext = new NorthwindEntities();

Category category = new Category();
category.CategoryName = "Test Category";

Product firstProduct = new Product();
firstProduct.ProductName = "Test Product 1";

Product secondProduct = new Product();
secondProduct.ProductName = "Test Product 2";

category.Products.Add( firstProduct );
category.Products.Add( secondProduct );

dbContext.AddToCategorySet( category );
dbContext.SaveChanges();

 Delete a Record from the Database :-

The code below demonstrates you how to delete all “Test” products from the database

NorthwindEntities dbContext = new NorthwindEntities();
var query = from p in dbContext.ProductSet
           where p.ProductName.Contains( "Test" )
           select p;
foreach ( Product p in query )
   dbContext.DeleteObject( p );
dbContext.SaveChanges();

Hope this helps

Good Luck