您的位置:首页 > 数据库

LINQ to SQL 不使用O/R设计器建表对象

2009-10-11 19:24 211 查看
创建自己的定制对象


首先要建立一个用于展示Customer的类,代码如下:


using System.Data.Linq.Mapping;  //需要加此引用

namespace LINQtoSQL
{
[Table(Name = "Customers")]  //制定Table特性表示表类,Name定义了在数据库中使用的表名
public class Customer
{
[Column(IsPrimaryKey = true, Name = "CustomerID")]//映射数据库中的列,并标识主键
public string MyCustomerID { get; set; }
[Column]
public string CompanyName { get; set; }
//[Column]
//public string ContactName { get; set; }
//[Column]
//public string ContactTitle { get; set; }
//[Column]
//public string Address { get; set; }
//[Column]
//public string City { get; set; }
//[Column]
//public string Region { get; set; }
//[Column]
//public string PostalCode { get; set; }
[Column]
public string Country { get; set; }
//[Column]
//public string Phone { get; set; }
//[Column]
//public string Fax { get; set; }
}
}
用定制的对象和LINQ进行查询


public void CustomObject()
{
// using ExecuteQuery
//获得一个DataContext对象,注意他使用的是DataContext
DataContext dc = new DataContext(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString());

dc.Log = Console.Out; //将使用的SQL输出到控制台

Table<Customer> myCustomers = dc.GetTable<Customer>();

foreach (Customer item in myCustomers)
{
Response.Write(item.CompanyName + " | " + item.Country + "<br />");
}
}



LINQ to SQL 使用DataContext对象在SQL Server 数据库上执行查询,把返回的行转换为强类型的Customer对象,这就允许迭代Table 对象集合中的每个Customer 对象,获得需要的信息。

用查询限制所查询的列

如果你定义的对象仅包含有限的属性,那么在查询的时候查询的结果也会根据属性进行返回对应个数结果列。

使用列名

列名必须要和属性名一致,否则会报错,为了解决这个问题,需要加入Name指定才行。

[Column(IsPrimaryKey = true, Name = "CustomerID")]//映射数据库中的列,并标识主键 public string MyCustomerID { get; set; }

创建自己的DataContext对象

创建自己的DataContext对象,就是Northwind.designer.cs 的一个子集,可以让这个类管理对数据库的连接,最简单形式代码如下。

using System.Data.Linq;
using System.Configuration;

namespace LINQtoSQL
{
public class MyNorthwindDataContext : DataContext
{
public Table<Customer> Customers;

public MyNorthwindDataContext()
: base(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString())
{
//调用基类实现初始化
}
}
}



 

使用自定义DataContext

 

public void MyselfDataContext()
{
// using ExecuteQuery
//获得一个DataContext对象,注意他使用的是DataContext
MyNorthwindDataContext dc = new MyNorthwindDataContext();

Table<Customer> myCustomers = dc.Customers;

foreach (Customer item in myCustomers)
{
Response.Write(item.CompanyName + " | " + item.Country + "<br />");
}

}



 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: