Skip to content

Talk.Linq.Extensions_demo

农码一生 edited this page Mar 11, 2017 · 2 revisions

查看代码

示例:
先执行Install-Package Talk.Linq.Extensions


导入命名空间 using Talk.Linq.Extensions

例1WhereIf

var students = await db.Students
     .WhereIf(!string.IsNullOrEmpty(name), t => t.Name == name)
     .ToListAsync();

例2PageBy(分页)

db.Students.OrderBy(t => t.Name).PageBy(10, 15).ToList();

例3OrderBy(传字符串)

db.Students.AsNoTracking().OrderBy("name asc,age desc").ToList();

例4And Or Lamdba拼接

Expression<Func<Student, bool>> expression = t => t.Name == "张三";
expression = expression.Or(t => t.Age == "18");
expression = expression.And(t => t.Teachers.Count() > 2);
db.Students.Where(expression).ToList();

例5select<T>

在程序第一次运行是执行Initialize :如Global.asax文件的Application_Start方法
Initialize 传入type数组,如:new Type[] { typeof(StudentDto), typeof(ScoreDto) }
更好的方式是使用反射的方式传入有Dto的程序集中的类型集合
AutoMapperModule.Initialize(Assembly.GetExecutingAssembly().ExportedTypes);
//特性映射
[AutoMap(typeof(Student))]
public class StudentDto
{
    public string Name { get; set; }
    public string Age { get; set; }
}
//查询出来的数据类型直接变成了Dto,且生成的sql也是按需查询的。
List<StudentDto> students1 = await db.Students
   .WhereIf(!string.IsNullOrEmpty(name), t => t.Name == name)
   .Select<StudentDto>()
   .ToListAsync();

例6更加复杂的映射

public class StudentDto
{
    public string Name { get; set; }
    public string Age { get; set; }
    public IEnumerable<ScoreDto> Scores { get; set; }

    [AutoMap(typeof(Score))]
    public class ScoreDto
    {
        public int Id { get; set; }
        public int StudentId { get; set; }

        public int MathematicsFraction { get; set; }

        public DateTime CreateTime { get; set; }
    }
}

[AutoMapProfile]
public class StudentDtoProfile : Profile
{
    public StudentDtoProfile()
    {
        //这里进行复杂的映射
        CreateMap<Student, StudentDto>().ForMember(t => t.Scores, f => f.MapFrom(m => m.Scores.Where(s => s.MathematicsFraction >= 60)));
    }
}

//查询出来的数据类型直接变成了Dto,且生成的sql也是按需查询的。
List<StudentDto> students1 = db.Students
   .WhereIf(!string.IsNullOrEmpty(name), t => t.Name == name)
   .Select<StudentDto>()
   .ToList();

Clone this wiki locally