LINQ: Perform CRUD operations by using ADO.NET Entity FrameWork

Suwarna
Posted by in LINQ category on for Beginner level | Points: 250 | Views : 20343 red flag
Rating: 3 out of 5  
 1 vote(s)

Entity Data Model (EDM) is bridge between application and database. LINQ(Language Integated Query) to entity which performs CRUD operations against the Entity Data Model(EDM)


 Download source code for LINQ: Perform CRUD operations by using ADO.NET Entity FrameWork

Introduction

Entity framework is model driven. Entity framework is conceptual model  that works with database,eliminating gap between data and application. Entity Framework enables to perform CRUD operations. With the help of entity model simply query against  entity.EDM or ntity Data model is foundation of entity framework.EDM is  bridge between application and datadbase(sql server). It is capabilteto access the data in oo fasion.Table acts as the object and field of tables act as property. Each Entity maped to single database table

LINQ (Language Integated Query) offers a unifirmly way to access and manage the data irrespective of datasource like XML,Object collection, database.We can use LINQ to entity which performs CRUD operations against the Entity Data Model(EDM). It also enables to create strongly typed and composable queries against EDM.

Using the code

Software Requirements: Visual Studio (3.5/4.0), SQL Server 2005

Step1:Create DataBase In SQL Server

Create Table StockMaster :Query

Create table StockMaster
(
ItemCode varchar(5) NOT NULL PRIMARY KEY,
ItemName varchar(50) NOT NULL,
Stock int,
float float

)

Step2:Create New Application 

Start Microsoft Visual Studio => File=> New=> Project => Choose Language(c#)=> Choose Application(indow Application )=>0k

Step3:  Create Entity data model  from the existing database connection

Solution Explorer =>right click on project => Add  => New Item. Select the Data Template => ADO.NET Entity Data Model and click Add.



The Entity Data Model Wizard appears. Choose ‘Generate From Database’ and click Next 



You have to now choose your DataBase Connection.


Our Entity Connection Settings will be stored in the App.Config file as ‘eguardEntities'. You can change the name to anything else you want. Click Next

choose the Database Objects You want to include in your Entity Data Model (EDM).The checkbox ‘Pluralize or singularize generated object names’ gives us the ability to pluralize or singularize object names. This is new to EF 4.0 and is a welcome change, as in EF 3.5, not being able to rename/pluralize objects in the model, caused a great deal of confusion.Click Finish to complete the wizard.

The .edmx  design looks like.

 

Step4: Perform CRUD operations by using EDM


Code  Description 


Create Instance of DataContext

eguardEntities EguardEntities=new eguardEntities ();

Get Data from the DataBase through Entity Framework

public  object   GetStockMaster()
        {
            var v=from sm in EguardEntities .StockMasters
                  select sm;
            return v;
       }


GetStockMaster() Method returns Object datatype. object  binds to Datagridview 

 var V=    StockMaster.GetStockMaster();
           stkMaterGridview.DataSource = V;


Delete records From StockMaster through Entity Framework


DeleteObject() method of EntitySet to delete the object.

SaveChanges() method on the context to reflect the changes back to database.


public bool DeleteStockMaster(string ItemCodes)
       {
           try
           {
          foreach(var sm in EguardEntities.StockMasters.Where(p1=>p1.ItemCode.Equals(ItemCodes)))
               {
                   EguardEntities.DeleteObject(sm);
  }
  EguardEntities.SaveChanges();
               return true;
 
           }
           catch(Exception ex)
           {
               return false;
           }
 
       }
 

 


Insert StockMaster through entity framework


Entity in the entity model which is StockMaster. Create instance of StockMaster.Then we can set values properties like ItemCode, ItemName, Rate, Stock.I have been set these value statically. You can set these value dynamically.

               StockMaster stockmaster = new StockMaster();
               stockmaster.ItemCode = "rg";
               stockmaster.ItemName = "Register";
               stockmaster.Rate = 20;
               stockmaster.Stock = 12;

 

 

ObjectContext itself provides an AddObject() method which can be used as


AddObject("StockMasters",stockmaster);
AddObject() passes 2 parameters. we need to provide the Entityset(StockMastersname as the first parameter . 

SaveChanges() method of the context to reflect the changes back to the databaseIt returns Integer value.

int numberOfAffectedRows = EguardEntities.SaveChanges();

 

 

        public int  InsertStockMaster(
{
           try
           {
               StockMaster stockmaster = new StockMaster();
               stockmaster.ItemCode = "rg";
               stockmaster.ItemName = "Register";
               stockmaster.Rate = 20;
               stockmaster.Stock = 12;
           
 
               //er.AddToOrderDetails(o);
               EguardEntities.AddObject("StockMasters", stockmaster);
  int numberOfAffectedRows = EguardEntities.SaveChanges();
               if(numberOfAffectedRows>0)
               {
                   return numberOfAffectedRows;
               }
               else
                   return 0;
           }
 
           catch(Exception ex)
           {
               return 0;
           }
 
 
 
 
 
       }



Perform Update Operations Using Entity Framework

  varv = (from stkmaster in
EguardEntities.StockMasters where
stkmaster.ItemCode.Equals(ItemCodes) select
stkmaster).ToList<StockMaster>();

 

This LINQ query returns record  which save in v variable. Before Update any record  We have to delete the object using deleteObject and then save these changes in database by calling SaveChanges() method. 

EguardEntities.DeleteObject(stockMaster);

        

       public void UpdateStockMaster(stringItemCodes)

       {         var v = (from stkmaster in EguardEntities.StockMasters where stkmaster.ItemCode.Equals(ItemCodes) select

stkmaster).ToList<StockMaster>();

foreach (StockMaster stockMaster  in v)

{

EguardEntities.DeleteObject(stockMaster);

EguardEntities.SaveChanges();

stockMaster.ItemName ="Ups";

EguardEntities.AddObject("StockMasters", stockMaster);

EguardEntities.SaveChanges();

}

   }

   }

}

 

 



 WHOLE CODE  stockMaster.CS

  

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace WindowsFormsApplication5

{

class stockMaster

    {

        eguardEntities EguardEntities=new eguardEntities ();

        //Get Data from StockMaster

      public  object   GetStockMaster()

        {

            var v=from sm in EguardEntities .StockMasters select sm;

          return v;

        }

//Delete Data from StockMaster insert

       public bool DeleteStockMaster(string ItemCodes)

       {

          try

          {

          foreach(var sm in EguardEntities.StockMasters.Where(p1=>p1.ItemCode.Equals(ItemCodes)))

               {

               EguardEntities.DeleteObject(sm);

               }

               EguardEntities.SaveChanges();

               return true;

           }

         catch(Exception ex)

           {

               return false;

           }

       }


//insert Data from Stock Master

     public int InsertStockMaster()

       {

           try

           {

              StockMaster stockmaster = new StockMaster();

               stockmaster.ItemCode = "rg";

               stockmaster.ItemName = "Register";

               stockmaster.Rate = 20;

               stockmaster.Stock = 12;

   

               //Add

               EguardEntities.AddObject("StockMasters", stockmaster);

               int numberOfAffectedRows = EguardEntities.SaveChanges();

               if(numberOfAffectedRows>0)

               {

                   return numberOfAffectedRows;

               }

               else

                   return 0;

           }

          catch (Exception ex)

           {

               return 0;

           }

       }

//Update StockMaster

       public void UpdateStockMaster(string ItemCodes)

       {

           var v = (from stkmaster in EguardEntities.StockMasters

where stkmaster.ItemCode.Equals(ItemCodes) 

select stkmaster).ToList<StockMaster>();

foreach (StockMaster stockMaster  in v)

{

    EguardEntities.DeleteObject(stockMaster);

    EguardEntities.SaveChanges();

    stockMaster.ItemName ="Ups";

   EguardEntities.AddObject("StockMasters", stockMaster);

    EguardEntities.SaveChanges();

}


      }

    }

}

Hope you liked this article, do write your feedback and comments.

Thanks
Page copy protected against web site content infringement by Copyscape

About the Author

Suwarna
Full Name: Suwarna Bhosale
Member Level: Starter
Member Status: Member
Member Since: 4/14/2013 3:50:22 AM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Saratvaddilli on: 4/22/2013 | Points: 25
nice article
Posted by: Ankitsrist on: 4/24/2013 | Points: 25
nice article....
Posted by: Narla.Venkatesh on: 5/22/2013 | Points: 25
nice article..
Posted by: Rasik on: 5/22/2013 | Points: 25
Nicely explained Entity framework CRUD operation
Posted by: Rupalihartalkar on: 8/19/2013 | Points: 25
Concept is very nicely explained. Very good for beginner with LINQ.

Login to post response

Comment using Facebook(Author doesn't get notification)