SqlSugar/Src/Asp.Net/SqlServerTest/Demos/G_Mapper.cs

65 lines
2.0 KiB
C#
Raw Normal View History

2018-10-14 09:26:53 +08:00
using OrmTest.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest.Demo
{
2018-10-14 13:10:08 +08:00
public class Mapper : DemoBase
2018-10-14 09:26:53 +08:00
{
public static void Init()
{
var db = GetInstance();
//auto fill ViewModelStudent3
var s11 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id)
.Select<ViewModelStudent3>().ToList();
2018-10-14 13:10:08 +08:00
var s12 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select<ViewModelStudent3>()
.Mapper((it, cache) =>
{
2018-10-14 13:24:16 +08:00
var allSchools = cache.GetListByPrimaryKeys<School>(vmodel => vmodel.SchoolId);
//sql select shool where id (inViewModelStudent3[0].SchoolId , ViewModelStudent3[1].SchoolId...
2018-10-14 13:10:08 +08:00
2018-10-14 13:20:10 +08:00
//Equal to allSchools
2018-10-14 13:10:08 +08:00
//var allSchools2= cache.Get(list =>
// {
// var ids=list.Select(i => it.SchoolId).ToList();
// return db.Queryable<School>().In(ids).ToList();
//});Complex writing metho
2018-10-14 13:20:10 +08:00
/*one to one*/
//Good performance
it.School = allSchools.FirstOrDefault(i => i.Id == it.SchoolId);
2018-10-14 13:10:08 +08:00
2018-10-14 13:20:10 +08:00
//Poor performance.
//it.School = db.Queryable<School>().InSingle(it.SchoolId);
2018-10-14 13:10:08 +08:00
2018-10-14 13:20:10 +08:00
/*one to many*/
it.Schools = allSchools.Where(i => i.Id == it.SchoolId).ToList();
/*C# syntax conversion*/
2018-10-14 13:15:11 +08:00
it.Name = it.Name == null ? "null" : it.Name;
2018-10-14 13:10:08 +08:00
}).ToList();
var s13 = db.Queryable<Student, School>((st, sc) => st.SchoolId == sc.Id).Select<ViewModelStudent3>()
.Mapper((it, cache) =>
{
it.Schools = db.Queryable<School>().Where(i => i.Id == it.SchoolId).ToList();
}).ToList();
2018-10-14 09:26:53 +08:00
}
}
}