LightSpeed的批量更新和批量删除

1.Update
对于批量操作 无论是Update还是Remove  都是使用LightSpeed的Query对象来完成。

注:Student是要进行Update的表(实体),StuName是表Student中用于查询的

var stuQuery = new Query(
    typeof(Student),
    Entity.Attribute("StuName") == "老王"
);

这个Query对象相当于一个Where。具体的Set语句是在下面这个代码里实现

dbContext.Update(stuQuery, new { Age = 25 });

 翻译过来就是,将StuName等于“老王”的Student的Age更新为25.

要注意的是 ,上面的更新对象是匿名类型,如果某一个属性需要更新为null的话会报错【无法将<null>赋予匿名类型属性】

这就需要用一个类或结构来承载。如下

dbSchool.Update(stuQuery, new AgeStruct { Age = null });

struct AgeStruct
{
    public int? Age { set; get; }
}

2.Remove

 批量删除与批量更新几乎一样,区别在于最后一步使用的是Remove方法,而不是Update。

var query = new Query(typeof(Student), Entity.Attribute("Id")==1);
DBContext.Remove(query);

3. 以上两种情况使用的Query,第二个参数都是一个QueryExpression对象,用于筛选数据。如果有多个筛选条件,则把这些条件用 && 和||  拼接起来即可。

QueryExpression qe = Entity.Attribute("Id") == 1 || Entity.Attribute("Id") == 2;
var query = new Query(typeof(Student), qe);
dbPlatform.Remove(query);

4.筛选条件的使用也是很灵活的。 如 == , in ,> ,<之类的。以下列举常用的一些:

//in 用法比较特别,方法需要的参数是一个object数组
object[] idArray = new List<int>{1,2,3,4,5,6,7,8}.Where(s => s % 2 == 0).Select(s => s as object).ToArray();
QueryExpression qe = Entity.Attribute("Id").In(idArray);

//基本使用
qe = Entity.Attribute("Id") == 1;
qe = Entity.Attribute("Id") > 3;
qe = Entity.Attribute("Id") < 5;
qe = Entity.Attribute("Id") != 0;

// Upper,Lower,Like
qe = Entity.Attribute("Name").Upper().Like("ray");
// Function  使用数据库中的函数
qe = Entity.Attribute("Age").Function(0, "Power", 3) < 20;
//Between
qe = Entity.Attribute("Age").Between(1, 33);
原文地址:https://www.cnblogs.com/TiestoRay/p/4581573.html