设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 892|回复: 1

Using LINQ to SQL in place of SQL Statements in C#

[复制链接]
发表于 2011-5-27 08:30:07 | 显示全部楼层 |阅读模式
本帖最后由 demo 于 2011-5-28 00:46 编辑

ASP.NET Database Tutorial

This tutorial will show you how to use LINQ to SQL in ASP.NET 3.5 to manipulate database data without using SQL Statements. C# version.

With ASP.NET 2.0 we were limited in our ways of connecting to a database, with SQL and Access databases the most popular to use. Not many developers enjoy working with SQL statements - having to translate between that and the scripting language. But now, with ASP.NET 3.5, we have been introduced to LINQ. LINQ provides us with a way of communicating directly with a database in the code - no need to translate into SQL. LINQ also comes in a variety of flavors, allowing us to connect to numerous data sources, not only databases.

In this tutorial, we will be using LINQ to SQL to interact with a SQL Server Database. We will add the ability to add new records to the database, as well as edit and delete existing records - all without using any SQL statements. To do this, we will need to create a LINQ to SQL Class to represent our database, but luckily for us, Visual Studio does the hard work for us.

Let's start by creating a new C# web application project in Visual Studio .NET 2008, and then add a new database by right-clicking the App_Data folder in Solution Explorer and choosing Add New Item.. SQL Server Database. We will add one table, tblEmployees, with three columns - id, name, and position. We will make the id the Primary Key and also the Identity Specification (in the Properties Window).

Once we have done this, save the table and make sure the Connection String is in the Web.config:

<connectionStrings>
        <add name="DatabaseConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>  

Next, right-click the project in Solution Explorer and choose Add ASP.NET Folder > App_Code. Then right-click the App_Code folder and choose Add New Item.. LINQ to SQL Classes. Give the name Employees. This is the class that will represent our database and that we will use LINQ to interact with.

We should be provided with a design view of the Object Relation Designer. Drag onto the designer the table from Server Explorer, then save.

Once saved, we can close the class - VS will create the methods based on our graphical structure. Next, we will extend this class with our own methods, which we will use to add, edit and delete database data. Right-click the App_Code folder once more and choose Add New Item.. Class. Give it the name Employees, and we should be provided with a new, empty C# class. Let's start with the Select statement. You will notice that LINQ statements are similar to SQL, but they interact with the class we created earlier, and then commit changes back to the database.

  
public static IEnumerable Select()
{
    EmployeesDataContext db = new EmployeesDataContext();

    return db.tblEmployees.OrderBy(e=>e.id);
}  


Instead of interacting directly with the database, we instantiate the DataContext class and make a selection of all the data, ordered by the id column using a Lambda Expression.

Now we can move onto the Insert method:

public static void Insert(tblEmployee employeeToAdd)
{
    EmployeesDataContext db = new EmployeesDataContext();

    db.tblEmployees.InsertOnSubmit(employeeToAdd);
    db.SubmitChanges();
}    

This method will be used by the FormView control to add a new record to the database. Using LINQ makes it so simple to do this, as it manages our database connection and data types, etc. All we need to tell it to do is to add, and what to add.
Now we can add the method that will allow us to update records using the built-in GridView update feature:

      
public static void Update(tblEmployee oldEmployee, tblEmployee newEmployee)
{
    EmployeesDataContext db = new EmployeesDataContext();

    db.tblEmployees.Attach(newEmployee,oldEmployee);
    db.SubmitChanges();
}    

Using the Attach method of the table class, we are able to supply the data necessary to update the database, then SubmitChanges commits changes back to the database.

Finally, we can write the method to delete records from the database:

public static void Delete(tblEmployee employeeToDelete)
{
    EmployeesDataContext db = new EmployeesDataContext();

    db.tblEmployees.Attach(employeeToDelete);
    db.tblEmployees.DeleteOnSubmit(employeeToDelete);
    db.SubmitChanges();
}    

The entire code is as follows:

  
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Data.Linq;

/// <summary>
/// Extension of Employees.dbml
/// </summary>
public partial class Employees
{
        public static void Insert(tblEmployee employeeToAdd)
        {
                EmployeesDataContext db = new EmployeesDataContext();
               db.tblEmployees.InsertOnSubmit(employeeToAdd);
               db.SubmitChanges();
        }

    public static IEnumerable<tblEmployee> Select()
    {
        EmployeesDataContext db = new EmployeesDataContext();
        return db.tblEmployees.OrderBy(e=>e.id);
    }

    public static void Update(tblEmployee oldEmployee, tblEmployee newEmployee)
    {
        EmployeesDataContext db = new EmployeesDataContext();
        db.tblEmployees.Attach(newEmployee,oldEmployee);
        db.SubmitChanges();
    }

    public static void Delete(tblEmployee employeeToDelete)
    {
        EmployeesDataContext db = new EmployeesDataContext();
        db.tblEmployees.Attach(employeeToDelete);
        db.tblEmployees.DeleteOnSubmit(employeeToDelete);
        db.SubmitChanges();
    }
}  

Now that we are now done extending the LINQ to SQL Class, we can work on implementing the functionality into our ASPX page. Firstly, let's add the controls we will be using:

<form id="form1" runat="server">
    <asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" DataSourceID="ODS1">
        <InsertItemTemplate>



        </InsertItemTemplate>
    </asp:FormView>


    <asp:GridView ID="GridView1" runat="server" DataSourceID="ODS1" Width="400px" />
    <asp:ObjectDataSource ID="ODS1" runat="server" />
</form>    

We set both controls DataSourceID to that of the ObjectDataSource, but we also need to set the method attributes to the ones we just created in the class. We do this by assigning the TypeName of the DataSource to our partial class, and then the methods:

      
<asp:ObjectDataSource ID="ODS1" runat="server" TypeName="Employees" DataObjectTypeName="tblEmployee"
        SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update" DeleteMethod="Delete"

        ConflictDetection="CompareAllValues" OldValuesParameterFormatString="oldEmployee" />

Finally, we build the template of our FormView and also enable the Edit and Delete buttons on our GridView:

<form id="form1" runat="server">
    <asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" DataSourceID="ODS1">
        <InsertItemTemplate>
            <asp: Label ID="lblName" runat="server" Text="Employee Name:" AssociatedControlID="txtName" /><br />
            <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>' /><br />
            <asp: Label ID="lblPosition" runat="server" Text="Position:" AssociatedControlID="txtPosition" /><br />
            <asp:TextBox ID="txtPosition" runat="server" Text='<%# Bind("position") %>' /><br />
            <asp:Button ID="btnInsert" runat="server" Text="Add" CommandName="Insert" />
        </InsertItemTemplate>
    </asp:FormView>
   
    <asp:GridView ID="GridView1" runat="server" DataSourceID="ODS1" Width="400px"
        DataKeyNames="id" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" />
   
    <asp:ObjectDataSource ID="ODS1" runat="server" TypeName="Employees" DataObjectTypeName="tblEmployee"
        SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update" DeleteMethod="Delete"
        ConflictDetection="CompareAllValues" OldValuesParameterFormatString="oldEmployee" />

</form>   

Now when we run this web application, we will be presented with a table of data from the database, and the ability to add new records, edit existing records and also delete records from the database. All this functionality without dealing directly with SQL.

http://www.aspnettutorials.com/tutorials/database/linq-to-sql-add-edit-delete-cs.aspx


发表于 2011-6-1 22:58:51 | 显示全部楼层
楼主好帖 不回不行啊 哈!

为了好帖我沉闷一天的手终于控制不了要去回帖了,好了,我回了....



三仙矛草,三仙矛草,三仙矛草,三仙矛草
发表于 2012-1-16 10:04:23
顶你一下,好贴要顶!












策一知产
支持 反对

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-26 11:09 , Processed in 0.014422 second(s), 17 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表