您的位置:首页 > 编程语言 > ASP

【ASP.NET MVC2】LINQ to SQL演练

2010-12-07 12:38 316 查看
以下演练来自Visual Studio 2010中的帮助文档。

演练需要SQL Server的NorthWind示例数据库。 示例4需要使用Windows SDK中的SqlMetal命令行工具为NorthWind数据库生成类文件。





/*
 *  演练:简单对象模型和查询 (C#) (LINQ to SQL)
 *  
 * 本演练由六项主要任务组成:
      o 在 Visual Studio 中创建 LINQ to SQL 解决方案。
      o 将类映射到数据库表。
      o 指定类中的属性表示数据库列。
      o 指定到 Northwind 数据库的连接。
      o 创建针对该数据库运行的简单查询。
      o 执行查询并观察结果。
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace _001
{
    [Table(Name = "Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey=true)]
        public string CustomerID {get; set;}
        [Column]
        public string City  {get; set;}
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 数据库连接
            DataContext db = new DataContext(@"C:/SQL SERVER 2000 SAMPLE DATABASES/NORTHWND.MDF");
            Table<Customer> Customers = db.GetTable<Customer>();
            // 创建延迟查询
            db.Log = Console.Out;
            IQueryable<Customer> custQuery = from cust in Customers
                                                                                where cust.City == "London"
                                                                                select cust;
            // 执行实际查询,并输出
            foreach (Customer c in custQuery)
            {
                Console.WriteLine("ID={0},  City={1}", c.CustomerID, c.City);
            }
            Console.ReadKey();
        }
    }
}










/*
 * 演练:跨关系查询 (C#) (LINQ to SQL)
 * 
 * 本演练由三项主要任务组成:
     o 添加一个实体类以表示 Northwind 示例数据库中的 Orders 表。
     o 向 Customer 类补充一些批注,以增强 Customer 和 Order 类之间的关系。
     o 创建并运行查询以测试能否通过使用 Customer 类获取 Order 信息。 
 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace _002
{
    // 对 Customer 类进行批注,以指示它与 Order 类的关系。 
    // (这种添加批注的操作并非绝对必需的,因为定义任一方向上的关系都足以满足创建链接的需要。
    // 但添加此批注确实便于您在任一方向上定位对象。)
    [Table(Name = "Customers")]
    public class Customer
    {
        private EntitySet<Order> _Orders;
        public Customer() { this._Orders = new EntitySet<Order>(); }
        [Column(IsPrimaryKey = true)]
        public string CustomerID { get; set; }
        [Column]
        public string City { get; set; }
        [Association(Storage = "_Orders", OtherKey = "CustomerID")]
        public EntitySet<Order> Orders
        {
            get { return this._Orders; }
            set { this._Orders.Assign(value); }
        }
    }
    // Order.Customer 作为外键与 Customer.CustomerID 相关。 
    [Table(Name = "Orders")]
    public class Order
    {
        //private string _OrderID;
        //private string _CustomerID;
        private EntityRef<Customer> _Customer;
        public Order() { this._Customer = new EntityRef<Customer>(); }
        [Column( IsPrimaryKey=true, IsDbGenerated=true)]
        public int OrderID { get; set; }
        //[Column(Storage = "_CustomerID")]
        [Column(DbType = "NChar(5)")]
        public string CustomerID { get; set; }
        [Association(Storage = "_Customer", ThisKey = "CustomerID")]
        public Customer Customer
        {
            get { return this._Customer.Entity;  }
            set { this._Customer.Entity = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 数据库连接
            DataContext db = new DataContext(@"C:/SQL SERVER 2000 SAMPLE DATABASES/NORTHWND.MDF");
            Table<Customer> Customers = db.GetTable<Customer>();
            // 创建延迟查询
            //db.Log = Console.Out;
            // 现在您可以直接从 Customer 对象访问 Order 对象,或反过来进行访问。 
            // 您不需要在客户和订单之间具有显式联接。
            // Query for customers who have placed orders.
            var custQuery = from cust in Customers
                                            where cust.Orders.Any()
                                             select cust;
            // 执行实际查询,并输出
            foreach (var c in custQuery)
            {
                Console.WriteLine("ID={0},  Qty={1}", c.CustomerID, c.Orders.Count);
            }
            Console.ReadKey();
        }
    }
}










/*
 * 演练:创建数据库的强类型化视图
  从数据库的强类型化视图着手要容易得多。通过将 DataContext 对象强类型化,
   您无需调用 GetTable。 当您使用强类型化的 DataContext 对象时,您可以在所有查询中使用强类型化表。 
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace _003
{
    // 强类型的DataContext
    public class Northwind : DataContext
    {
        // Table<T> abstracts database details per table/data type.
        public Table<Customer> Customers;
        public Northwind(string connection) : base(connection) { }
    }
    [Table(Name = "Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey = true)]
        public string CustomerID { get; set; }
        [Column]
        public string City { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 数据库连接
            Northwind db = new Northwind(@"C:/SQL SERVER 2000 SAMPLE DATABASES/NORTHWND.MDF");
            // 创建延迟查询
            //db.Log = Console.Out;
            IQueryable<Customer> custQuery = from cust in db.Customers
                                             where cust.City == "Seattle"
                                             select cust;
            // 执行实际查询,并输出
            foreach (Customer c in custQuery)
            {
                Console.WriteLine("ID={0}", c.CustomerID);
            }
            Console.ReadKey();
        }
    }
}










/* 
 * 演练:操作数据 (C#) (LINQ to SQL) 
 * 
 * 本演练由六项主要任务组成:
    在 Visual Studio 中创建 LINQ to SQL 解决方案。
    向项目添加数据库代码文件。
    创建新的客户对象。
    修改客户的联系人姓名。
    删除订单。
    将这些更改提交至 Northwind 数据库。
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _004
{
    class Program
    {
        static void Main(string[] args)
        {
            NORTHWND db = new NORTHWND(@"C:/SQL SERVER 2000 SAMPLE DATABASES/NORTHWND.MDF");
            //////////////////////////////////////////////////////////////////////////
            // 创建新实体
            //////////////////////////////////////////////////////////////////////////
            // Create the new Customer object.
            Customer newCust = new Customer();
            newCust.CompanyName = "AdventureWorks Cafe";
            newCust.CustomerID = "ADVCA";
            // Add the customer to the Customers table.
            db.Customers.InsertOnSubmit(newCust);
            Console.WriteLine("/nCustomers matching CA before insert");
            foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA")))
            {
                Console.WriteLine("{0}, {1}, {2}",
                    c.CustomerID, c.CompanyName, c.Orders.Count);
            }
            //////////////////////////////////////////////////////////////////////////
            // 更新实体
            //////////////////////////////////////////////////////////////////////////
            // Query for specific customer.
            // First() returns one object rather than a collection.
            var existingCust =
                (from c in db.Customers
                 where c.CustomerID == "ALFKI"
                 select c)
                .First();
            // Change the contact name of the customer.
            existingCust.ContactName = "New Contact";
           //////////////////////////////////////////////////////////////////////////
            // 删除实体
            //////////////////////////////////////////////////////////////////////////
            // Access the first element in the Orders collection.
            Order ord0 = existingCust.Orders[0];
            // Access the first element in the OrderDetails collection.
            OrderDetail detail0 = ord0.OrderDetails[0];
            // Display the order to be deleted.
            Console.WriteLine
                ("The Order Detail to be deleted is: OrderID = {0}, ProductID = {1}",
                detail0.OrderID, detail0.ProductID);
            // Mark the Order Detail row for deletion from the database.
            db.OrderDetails.DeleteOnSubmit(detail0);
            //////////////////////////////////////////////////////////////////////////
            // 将更改提交到数据库
            //////////////////////////////////////////////////////////////////////////
            // db.SubmitChanges();
            Console.ReadKey();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: