linq examples

Upload: spi321

Post on 06-Apr-2018

261 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/2/2019 Linq Examples

    1/29

    dcDataContext dc = new dcDataContext();{

    var Stud = from s in dc.Studentswhere s.sname.Contains("KrishnaRao")

    select s;GridView1.DataSource = Stud;GridView1.DataBind();

    }

    2) dcDataContext db = new dcDataContext();

    { var em = from e1 in db.empswhere e1.Empno == 1select e1;

    GridView1.DataSource = em;

    GridView1.DataBind();

    }

    3) or

    studDataContext db = new studDataContext();{

    var b = from b1 in db.Studentswhere b1.ClassID==1 | b1.Srno==1select b1;

    GridView1.DataSource = b;GridView1.DataBind();

    }

    4) using two tables (join method)

    studDataContext db = new studDataContext();{

    var b = from b1 in db.Students

  • 8/2/2019 Linq Examples

    2/29

    where b1.ClassID.Equals(3)| b1.Class.classname.Contains("Civil")

    select b1;

    GridView1.DataSource = b;GridView1.DataBind();

    }

    5)using And operator

    studDataContext db = new studDataContext();{

    var b = from b1 in db.Studentswhere

    b1.saddress.Contains("bangalore")&

    b1.Class.classname.Contains("Mechanical")select b1;

    GridView1.DataSource = b;GridView1.DataBind();

    }

    For updating,deleting and inserting linq query

    1)4 buttons2)And gridview

    protected void Page_Load(object sender, EventArgs e){

    showmethod();}

    protected void Button1_Click(object sender,EventArgs e){

    showmethod();}

    private void showmethod()

  • 8/2/2019 Linq Examples

    3/29

    {dcDataContext db = new dcDataContext();var em = from e1 in db.emps

    // where e1.Empno == 1orderby e1.ename descendingselect new { e1.Empno, e1.ename,

    e1.salary, e1.da };GridView1.DataSource = em;GridView1.DataBind();

    }protected void Button2_Click(object sender,

    EventArgs e){

    dcDataContext db = new dcDataContext();

    emp e2 = new emp { Empno = 15, ename ="Rohini", salary = 23451, da = 1300 };db.emps.InsertOnSubmit(e2);db.SubmitChanges();showmethod();

    }protected void Button3_Click(object sender,

    EventArgs e){

    dcDataContext db = new dcDataContext();emp e3 = db.emps.First(em3 =>

    em3.ename.StartsWith("Rohini"));e3.salary += 345;db.SubmitChanges();showmethod();

    }protected void Button4_Click(object sender,

    EventArgs e)

    { dcDataContext db = new dcDataContext();emp e3 = db.emps.First(em3 =>

    em3.ename.StartsWith("Haritha"));db.emps.DeleteOnSubmit(e3);db.SubmitChanges();showmethod();

  • 8/2/2019 Linq Examples

    4/29

    }

    2) protected void Page_Load(object sender, EventArgse)

    {Load_Data();

    }private void Load_Data(){

    dcDataContext dc = new dcDataContext();

    var Stud = from s in dc.Students

    select new{s.Srno,s.sname,s.saddress,s.ClassID,

    };

    GridView1.DataSource = Stud;GridView1.DataBind();

    }protected void Button1_Click(object sender,

    EventArgs e){

    dcDataContext dcx = new dcDataContext();

    var Stud = dcx.Students.Single(dc => dc.Srno ==

    4);

    Stud.sname = "Simona";

    try{

    dcx.SubmitChanges();

  • 8/2/2019 Linq Examples

    5/29

    Response.Write("Existing row is Updated");}catch (Exception ex){

    Response.Write(ex.Message);}Load_Data();

    }

    protected void Button2_Click(object sender,EventArgs e)

    { dcDataContext dcx = new dcDataContext();

    Student s=new Student();s.Srno=11;s.sname="Spandana";s.saddress="Guntur,AP";s.ClassID=5;dcx.Students.InsertOnSubmit(s);

    try

    {dcx.SubmitChanges();Response.Write("A new row is inserted");

    }catch (Exception ex){

    Response.Write(ex.Message);}

    Load_Data();

    }

    protected void Button3_Click(object sender,EventArgs e)

  • 8/2/2019 Linq Examples

    6/29

    {dcDataContext dcx = new dcDataContext();var s = dcx.Students.Single(s1 => s1.Srno ==

    10);

    dcx.Students.DeleteOnSubmit(s);

    try{

    dcx.SubmitChanges();Response.Write("One row is Deleted");

    }catch (Exception ex){

    Response.Write(ex.Message);}

    Load_Data();

    }

    So, just open Visual Studio and create a new C# website.

    Database design

    We need to create a database when the comments will be stored. Well just create adatabase with a single table that will keep the comments posted by the authors. We can

    create it in Server Explorer without leaving Visual Studio.

  • 8/2/2019 Linq Examples

    7/29

    Dont forget to set the Id field as an identity.

    Lets populate the database as well, so that well have some data to display, just execute

    these queries:

    INSERT INTO Comments(Author, Text)VALUES('John', 'ASP.NET 3.5 rocks!');

    INSERT INTO Comments

    (Author, Text)VALUES('Mary', 'ASP.NET 3.5 is so cool!');

    LINQ

    Then, we need to create a LINQ To SQL class that will be using for the data

    manipulations (retrieving and inserting). We open Website->Add New Item and choose

    LINQ To SQL Classes

  • 8/2/2019 Linq Examples

    8/29

    Then we open Server Explorer and drag and drop our table on the workspace.

  • 8/2/2019 Linq Examples

    9/29

    Now we just save this file and go futher, we can view the generated code though located

    in App_Code\Comments.dbml\Comments.designer.cs

    LinqDataSource

    Ok, its a time for create your webform that will hold all the content. Actually, it is

    already created by Visual Studio, we just have to add some content there.

    We are going to start with a data source, open Toolbox, expand the data section and find

    LinqDataSource there.

  • 8/2/2019 Linq Examples

    10/29

    Drag it to the webform. You will get the following code:

    Give it a more appopriate name, something like dsComments. Now switch to the Designview, click on the LinqDataSource weve just added and select Configure Data Source.

    Choose the only available data context object and click Next.

  • 8/2/2019 Linq Examples

    11/29

  • 8/2/2019 Linq Examples

    12/29

    Pretty simple, I would say.

    ListView

    Its time to add the ListView control. Its a new data bound control that enables you to

    have a full control of the rendered HTML code. Its also located in the Data section of

    Toolbox. Drag it and rename it to lvComments, also dont forget to assign a data source

    to it. You must get the following code:

    Then, we have to add the that will be the root template

    ASP.NET Guestbook

    Please, note the we have the div tag with id="itemPlaceholder" runat="server". They

    denote that ListView content will be placed in the place of that div, itemPlaceholder is

    the default ID of the content placeholder.

    To display out data we should add the element and place some content

    there

    says

    Its simply and has nothing new if you worked with other data bound controls. Lets add

    the separator element to separate the posts:

  • 8/2/2019 Linq Examples

    13/29

    Compile the website, you should you see a very simply webpage with just two comments

    by Mary and John that we added in the very beginning. Its cool, but what about

    enabling users to post comments? It also can be done by using LinqDataSource and

    ListView.

    First, add EnableInsert=True attribute to the LinqDataSource. Second, we need to add

    the insert item template to the ListView.

    Name:

    Text:


    Pay attetion at two things data binding in the input controls and the CommandName

    attribute in the button. If you compile the website right now, you wont see see the post

    form because you should define its position first, to do that add

    InsertItemPosition="FirstItem" to the ListView attributes, you can set it to LastItem

    however.

    Now compile the project and try posting some comments. Its working that is good.

    DataPager

    Its time to add a pagination and see another new control in action. It is called

    DataPager. Add the following code to the LayoutTemlate of the ListView:

    I suppose its pretty self-explanatory, PagedControlID defined the control we want topage, PageSize sets the number of entries per page. says

    that we want to have the list of the page numbers. Compile it and try it in the browser.

    I guess you noticed that it has an ugly postback in its URL. You can easily get rid of it by

  • 8/2/2019 Linq Examples

    14/29

    adding the QueryStringField attribute to the DataPager and of course by setting its value

    ;-).

    It looks much better now and you can send the link to the 10th page of your guestbook

    to a friend.

    Using LINQ to SQL (Part 1)

    Over the last few months I wrote a series of blog posts that covered some of the new language features

    that are coming with the Visual Studio and .NET Framework "Orcas" release. Here are pointers to theposts in my series:

    Automatic Properties, Object Initializer and Collection Initializers

    Extension Methods

    Lambda Expressions

    Query Syntax

    Anonymous Types

    The above language features help make querying dataa first class programming concept. We call thisoverall querying programming model "LINQ" - which stands for .NET Language Integrated Query.

    Developers can use LINQ with any data source. They can express efficient query behavior in theirprogramming language of choice, optionally transform/shape data query results into whatever format theywant, and then easily manipulate the results. LINQ-enabled languages can provide full type-safetyand compile-time checking of query expressions, and development tools can provide full intellisense,debugging, and rich refactoring support when writing LINQ code.

    LINQ supports a very rich extensibility model that facilitates the creation of very efficient domain-specificoperators for data sources. The "Orcas" version of the .NET Framework ships with built-in libraries thatenable LINQ support against Objects, XML, and Databases.

    What Is LINQ to SQL?

    LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework"Orcas" release, and which allows you to model a relational database using .NET classes. You can thenquery the database using LINQ, as well as update/insert/delete data from it.

    LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy way tointegrate data validation and business logic rules into your data model.

    Modeling Databases Using LINQ to SQL:

    http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspxhttp://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspxhttp://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspxhttp://weblogs.asp.net/scottgu/archive/2007/04/21/new-orcas-language-feature-query-syntax.aspxhttp://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx?CommentPosted=truehttp://en.wikipedia.org/wiki/Object-relational_mappinghttp://en.wikipedia.org/wiki/Object-relational_mappinghttp://weblogs.asp.net/scottgu/archive/2007/05/15/new-orcas-language-feature-anonymous-types.aspx?CommentPosted=truehttp://weblogs.asp.net/scottgu/archive/2007/04/21/new-orcas-language-feature-query-syntax.aspxhttp://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspxhttp://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspxhttp://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx
  • 8/2/2019 Linq Examples

    15/29

    Visual Studio "Orcas" ships with a LINQ to SQL designer that provides an easy way to model andvisualize a database as a LINQ to SQL object model. Using the LINQ to SQL designer I can easily createa representation of the sample "Northwind" database like below:

    My LINQ to SQL design-surface above defines four entity classes: Product, Category, Order andOrderDetail. The properties of each class map to the columns of a corresponding table in the database.Each instance of a class entity represents a row within the database table.

    The arrows between the four entity classes above represent associations/relationships between thedifferent entities. These are typically modeled using primary-key/foreign-key relationships in thedatabase. The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship. Strongly-typed properties will be added to the entity classes based onthis. For example, the Category class above has a one-to-many relationship with the Product class. Thismeans it will have a "Categories" property which is a collection of Product objects within that category.The Product class then has a "Category" property that points to a Category class instance that representsthe Category to which the Product belongs.

  • 8/2/2019 Linq Examples

    16/29

    The right-hand method pane within the LINQ to SQL design surface above contains a list of storedprocedures that interact with our database model. In the sample above I added a single"GetProductsByCategory" SPROC. It takes a categoryID as an input argument, and returns a sequenceof Product entities as a result. We'll look at how to call this SPROC in a code sample below.

    Understanding the DataContext Class

    When you press the "save" button within the LINQ to SQL designer surface, Visual Studio will persist out.NET classes that represent the entities and database relationships that we modeled. For each LINQ toSQL designer file added to our solution, a custom DataContext class will also be generated. ThisDataContext class is the main conduit by which we'll query entities from the database as well as applychanges. The DataContext class created will have properties that represent each Table we modeledwithin the database, as well as methods for each Stored Procedure we added.

    For example, below is the NorthwindDataContext class that is persisted based on the model we designedabove:

    LINQ to SQL Code Examples

    Once we've modeled our database using the LINQ to SQL designer, we can then easily write code towork against it. Below are a few code examples that show off common data tasks:

  • 8/2/2019 Linq Examples

    17/29

    1) Query Products From the Database

    The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects. Notehow the code is querying across the Product/Category relationship to only retrieve those products in the"Beverages" category:

    C#:

    VB:

    2) Update a Product in the Database

    The code below demonstrates how to retrieve a single product from the database, update its price, andthen save the changes back to the database:

    C#:

    VB:

  • 8/2/2019 Linq Examples

    18/29

    Note: VB in "Orcas" Beta1 doesn't support Lambdas yet. It will, though, in Beta2 - at which point theabove query can be rewritten to be more concise.

    3) Insert a New Category and Two New Products into the Database

    The code below demonstrates how to create a new category, and then create two new products andassociate them with the category. All three are then saved into the database.

    Note below how I don't need to manually manage the primary key/foreign key relationships. Instead, justby adding the Product objects into the category's "Products" collection, and then by adding the Categoryobject into the DataContext's "Categories" collection, LINQ to SQL will know to automatically persist theappropriate PK/FK relationships for me.

    C#

    VB:

  • 8/2/2019 Linq Examples

    19/29

    4) Delete Products from the Database

    The code below demonstrates how to delete all Toy products from the database:

    C#:

    VB:

    5) Call a Stored Procedure

  • 8/2/2019 Linq Examples

    20/29

    The code below demonstrates how to retrieve Product entities not using LINQ query syntax, but rather bycalling the "GetProductsByCategory" stored procedure we added to our data model above. Note thatonce I retrieve the Product results, I can update/delete them and then call db.SubmitChanges() to persistthe modifications back to the database.

    C#:

    VB:

    6) Retrieve Products with Server Side Paging

  • 8/2/2019 Linq Examples

    21/29

    The code below demonstrates how to implement efficient server-side database paging as part of a LINQquery. By using the Skip() and Take() operators below, we'll only return 10 rows from the database -starting with row 200.

    C#:

    VB:

    Summary

    LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you've definedyour data model you can easily and efficiently perform queries, inserts, updates and deletes against it.

    Solution Structure

    For this article we will need two projects. One is a data layer (created as a Class

    Library)which we will generate and the other is an ASP.NET Web Application. The solutions

    structure looks like this in Solution Explorer.

  • 8/2/2019 Linq Examples

    22/29

    Creating Data Layer

    Before we generate our data layer we must create a new connection in Server Explorer

    which points to Northwind database.

    We will now generate our data layer using LINQ To SQL. To do this you need to add a new

    item to the data layer project of type LINQ to SQL Classes. We will name it Northwind as

    shown below.

  • 8/2/2019 Linq Examples

    23/29

    After adding a LINQ to SQL Class we are presented with a designer surface. Here we can

    simply drag the tables which will become part of our data layer. For this article we will drag

    all tables on the designer by selecting them all in one go. Our designer should look like

    this after dragging all tables on it.

  • 8/2/2019 Linq Examples

    24/29

    We should now build our solution to make sure everything is okay. And thats it. We have

    successfully generated our data layer. In Solution Explorer we can see that we have two

    new files namely Northwind.dbml.layout and Northwind.designer.cs. We can also see that

    references required to compile and run our code have been added by Visual Studio.

  • 8/2/2019 Linq Examples

    25/29

    The .cs file contains the code for our data layer. Lets examine the code that has been

    generated for us. We will look at the Region class.

    The class itself is decorated with Table attribute and the Name property has been assigned

    the actual table name we have in our database. Region class also implements

    INotifyPropertyChanging and INotifyPropertyChanged interfaces. These interfaces are used

    for databinding. Region class also contains one property per column. Lets look at the

    RegionDescription property.

    Columns are decorated with Column attribute and values are passed in for Storage, DbType

    and CanBeNull which indicates if the column can be null or not.

  • 8/2/2019 Linq Examples

    26/29

    Using Data LayerNow that we have generated our data layer. We will work on ASP.NET web application where

    we will use our data layer. To keep things simple we will create a web forms to search for

    customers and display search results. We will also create a web form to insert new

    customers. Lets start by creating our web form for customer search. For this we will use

    the Default.aspx page. We will place few controls on the web form. These controls will give

    us search parameters and a button which will do the search and display results when

    clicked. This is what the form will look like after placing our controls.

    We will also place a GridView control on our form to display search results. We will now put

    in some code in our buttons click event handler to do the search and display results in

    GridView. Make sure that we have a reference to Data Layer project, System.Data.Linq and

    appropriate using statement. Here is what our button click event handler will contain.

    protectedvoidbuttonSearch_Click(objectsender, EventArgs e)

    {

    using(NorthwindDataContext context = newNorthwindDataContext())

    {

    var customers =

    from c incontext.Customers

    select c;

    gridViewCustomers.DataSource = customers;

    gridViewCustomers.DataBind();

    }

    }

  • 8/2/2019 Linq Examples

    27/29

    This code will query the customers table in northwind database and will return all

    customers. We will now modify it slightly to accept customer name and company name as

    parameters for our query. After modification our event handler looks like this.

    protectedvoidbuttonSearch_Click(objectsender, EventArgs e)

    {

    using(NorthwindDataContext context = newNorthwindDataContext())

    {

    var customers =

    from c incontext.Customers

    where (c.ContactName.Contains(textBoxCustomerName.Text.Trim())

    &&

    c.CompanyName.Contains(textBoxCompanyName.Text.Trim()))

    select c;

    gridViewCustomers.DataSource = customers;

    gridViewCustomers.DataBind();

    }

    }

    Our search results will now be filtered.

    Let us now created a data entry form for customers. We will insert a new web form in our

    ASP.NET project and call it CustomerEntry. To start with we will make sure that our form

    contains fields required to insert a customer. Our form after completion will look like this.

  • 8/2/2019 Linq Examples

    28/29

    We expect a new row to be inserted into customers table when Save Customer button is

    clicked. This code achieves data insertion into customers table for us.

    protected void buttonSave_Click(object sender, EventArgs e)

    {

    Using(NorthwindDataContext context=new NorthwindDataContext())

    {

    Customer customer=new Customer

    {

    CustomerID=textBoxCustomerID.Text,

    CompanyName=textBox CompanyName.Text,

  • 8/2/2019 Linq Examples

    29/29

    ContactName=textBox ContactName.Text,

    ContactTitle=textBoxContactTitle.Text,

    Address=textBoxAddress.Text,

    City

    Region

    PostalCode=

    Country=

    Phone=

    Fax=

    };

    Context.Customers.InsertOnSubmit(customer);

    Context.SubmitChanges();

    }

    }

    protectedvoid

    Similarly an existing row in database can be updated by first retrieving the data and then

    submitting it via DataContext.