ALinq 使用教程(七)ALinq 的扩展
2011-05-05 11:26 麦舒 阅读(964) 评论(0) 编辑 收藏 举报ALinq 在 Linq to SQL 的基本,做了一些扩展,使得它更为好用。
获取实体类的 DataContext 对象
选择Category 实体类,将 DataContext 设为 True 。
运行下面的代码:
static void Main(string[] args)
{
var dc = new NorthwindDataContext() { Log = Console.Out };
var category = dc.Categories.First();
Console.WriteLine(category.DataContext);
}
{
var dc = new NorthwindDataContext() { Log = Console.Out };
var category = dc.Categories.First();
Console.WriteLine(category.DataContext);
}
运行结果:
很明显,可以看到 category.DataContext 对象不为空,但是我们并没有在代码中给 category.DataContext 赋值,它怎么会不为空呢?我来看一下代码生成器生成的代码。
代码
// This method is called by the dataContext when the entity is created.
private void SetDataContext(ALinq.DataContext dataContext)
{
this.DataContext = ((NorthwindDataContext)(dataContext));
}
public NorthwindDataContext DataContext
{
get
{
return this._DataContext;
}
private set
{
this._DataContext = value;
}
}
private void SetDataContext(ALinq.DataContext dataContext)
{
this.DataContext = ((NorthwindDataContext)(dataContext));
}
public NorthwindDataContext DataContext
{
get
{
return this._DataContext;
}
private set
{
this._DataContext = value;
}
}
我们主意到 SetDataContext 这个方法,当一个实体被 DataContext 创建后,DataContext 便会通反射检索名称 SetDataContext 的方法,如果存在,则调用该方法。所以,尽管我闪并没有对 category.DataContext 赋值,但 DataContext 却通过调用 SetDataContext 对它进行了赋值。
批量更新、删除
代码
static void Main(string[] args)
{
var dc = new NorthwindDataContext() { Log = Console.Out };
dc.Categories.Update(o => new Category { Categoryname = "New Name" }, o => o.Categoryid == -1);
dc.Categories.Delete(o => o.Categoryid == -1);
}
{
var dc = new NorthwindDataContext() { Log = Console.Out };
dc.Categories.Update(o => new Category { Categoryname = "New Name" }, o => o.Categoryid == -1);
dc.Categories.Delete(o => o.Categoryid == -1);
}
运行结果:
使用 Linq 表达式插入数据
代码
static void Main(string[] args)
{
var dc = new NorthwindDataContext() { Log = Console.Out };
var categoryID = dc.Categories.Max(c => c.Categoryid) + 1;
dc.Categories.Insert(o => new Category
{
Categoryid = categoryID,
Categoryname = "Category Name",
Description = "Description"
});
}
{
var dc = new NorthwindDataContext() { Log = Console.Out };
var categoryID = dc.Categories.Max(c => c.Categoryid) + 1;
dc.Categories.Insert(o => new Category
{
Categoryid = categoryID,
Categoryname = "Category Name",
Description = "Description"
});
}
运行结果: