DataContext 类型(数据上下文)是System.Data.Linq命名空间下的重要类型 。用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方法和把实体的修改写入数据库,
1. 主要的功能:
l 以日志形式记录DataContext生成的SQL
l 执行SQL(包括查询和更新语句 )
l 创建和删除数据库
2. DataContext是实体与数据库之间的桥梁。
1) 定义映射到数据表的实体
using System.Data.Linq.Mapping;
[Table(Name = "Customers")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public string CustomerID {get; set;}
[Column(Name = "ContactName")]
public string Name { get; set; }
[Column]
public string City {get; set;}
}
如果没有指定Column特性的Name属性,那么系统会把属性名作为数据表的字段名,也就是说实体类的属性名就需要和数据表中的字段名一致。
2) DataContext类型把实体类和数据库中的数据进行关联
using System.Data.Linq;
DataContext ctx = new DataContext("server=xxx;database=Northwind;uid=xxx;pwd=xxx");
Table<Customer> Customers = ctx.GetTable<Customer>();
GridView1.DataSource = from c in Customers where c.CustomerID.StartsWith("A") select new {顾客ID=c.CustomerID, 顾客名=c.Name, 城市=c.City};
GridView1.DataBind();
3. 强类型DataContext
public class NorthwindDataContext : DataContext
{
public Table<Entities.ActionInstance> ActionInstances;
public NorthwindDataContext(IDbConnection connection)
: base(connection)
{
}
public NorthwindDataContext(string Connection)
: base(Connection)
{
}
}
//调用强类型DataContext
DAL.NorthwindDataContext context = new LinQ.DAL.NorthwindDataContext(@"server=EGOLABS\SQL2005;database=ZSITIMS2;uid=ZSITIMS2;pwd=ZSITIMS2;");
dataGridView1.DataSource = from c in context.ActionInstances
where c.ActionDate >= new DateTime(2010, 5, 1)
//orderby by c.ActionDate
select new { 操作名称 = c.ActionName, 操作标识 = c.ActionSign, 操作时间 = c.ActionDate };
4. 日志功能
//强类型
DAL.NorthwindDataContext context = new LinQ.DAL.NorthwindDataContext(@"server=EGOLABS\SQL2005;database=ZSITIMS2;uid=ZSITIMS2;pwd=ZSITIMS2;");
//日志功能
StreamWriter sw = new StreamWriter(@"F:\学习\LINQ\log.txt", true);
context.Log = sw;
//数据绑定
dataGridView1.DataSource = from c in context.ActionInstances
where c.ActionDate >= new DateTime(2010, 5, 1)
//orderby by c.ActionDate
select new { 操作名称 = c.ActionName, 操作标识 = c.ActionSign, 操作时间 = c.ActionDate };
sw.Close();
5. 探究查询
//探究查询
string strConn = @"server=EGOLABS\SQL2005;database=ZSITIMS2;uid=ZSITIMS2;pwd=ZSITIMS2;";
DAL.NorthwindDataContext context = new LinQ.DAL.NorthwindDataContext(strConn);
var strSQL = from c in context.ActionInstances
where c.ActionDate >= new DateTime(2010, 5, 1)
//orderby by c.ActionDate
select new { 操作名称 = c.ActionName, 操作标识 = c.ActionSign, 操作时间 = c.ActionDate };
DbCommand cmd = context.GetCommand(strSQL);
MessageBox.Show(cmd.CommandText+"\n");
foreach(DbParameter param in cmd.Parameters)
MessageBox.Show(string.Format("参数名:{0};参数值:{1};\n",param.ParameterName,param.Value));
Entities.ActionInstance ai = context.ActionInstances.First();
ai.ActionName = "XXXXX";
IList<object> queryText = context.GetChangeSet().Updates;
MessageBox.Show(((Entities.ActionInstance)queryText[0]).ActionName);
6. 执行查询
7. 创建数据库
8. 使用DbDataReader数据源
浙公网安备 33010602011771号