ข้ามไปที่เนื้อหา

Read

ตัวอย่างข้อมูล

public class SelectedFilter{
    public int Id { get; set; }
    public string? CampusId { get; set; }
    public string? CFacultyId { get; set; }
    public string? CDeptId { get; set; }
    public string? CSectionId { get; set; }
}

public static List<SelectedFilter> SelectedMockupList = new()
{
    new()
    {
        Id = 1,
        CampusId = "01",
        CFacultyId = "A1",
        CDeptId = "B1",
        CSectionId = "C1",
    },
    {
        Id = 2,
        CampusId = "02",
        CFacultyId = "A2",
        CDeptId = "B2",
        CSectionId = "C2",
    },
    {
        Id = 3,
        CampusId = "03",
        CFacultyId = "A3",
        CDeptId = "B3",
        CSectionId = "C3",
    },
    {
        Id = 4,
        CampusId = "04",
        CFacultyId = "A4",
        CDeptId = "B4",
        CSectionId = "C4",
    },
    {
        Id = 5,
        CampusId = "05",
        CFacultyId = "A5",
        CDeptId = "B5",
        CSectionId = "C5",
    },
    {
        Id = 6,
        CampusId = "05",
        CFacultyId = "A5-1",
        CDeptId = "B5-1",
        CSectionId = "C5-1",
    },
    {
        Id = 7,
        CampusId = "05",
        CFacultyId = "A5-2",
        CDeptId = "B5-2",
        CSectionId = "C5-2",
    },

};

จากกลุ่มข้อมูลเราสามารถใช้คำสั่ง LINQ เพื่อจัดการด้วยวิธีการ Asyn ได้ดังนี้

Filtering

ใช้สำหรับคัดกรองข้อมูลเฉพาะที่เราต้องการเท่านั้น ซึ่งคำสั่งที่สามารถใช้งานได้ ดังตัวอย่าง ในตาราง A

คำสั่ง ใช้สำหรับ ตัวอย่าง ผลลัพธ์
Where กรองข้อมูล
var strQry = SelectedFilter
.Where(s => s.CampusId = "01" || s.CampusId = "02")
.FirstOrDefaultAsync()
strQry = ข้อมูลของวิทยาเขตรหัส 01 หรือรหัส 02
Select ดึงข้อมูล
var strQry = SelectedFilter
.Select(x => x.CFacultyId)
.ToListAsync()
Distinct เอาเฉพาะตัวที่ซ้ำมาแค่ตัวเดียว
var strQry = SelectedFilter
.Distinct(x => x.CFacultyId)
.ToListAsync()
ได้ข้อมูลที่มีเฉพาะข้อมูลที่ไม่ซ้ำกัน
Take เอาข้อมูล
var take = 10;
var strQry = SelectedFilter
.Take(()=>take)
.ToListAsync()
Skip ข้ามข้อมูลไปกี่ข้อมูล
var skip = 10;
var strQry = SelectedFilter
.Skip(()=>skip)
.ToListAsync()

Ordering

คำสั่ง ใช้สำหรับ ตัวอย่าง ผลลัพธ์
OrderBy เรียงลำดับจากน้อยไปมาก (A-Z)
var strQry = SelectedFilter
.OrderBy(x => x.CampusId)
.ToListAsync();
OrderByDescending เรียงลำดับจากมากไปน้อย (Z-A)
var strQry = SelectedFilter
.OrderByDescending(x => x.CampusId)
.ToListAsync();

Grouping

คำสั่ง ใช้สำหรับ ตัวอย่าง ผลลัพธ์
GroupBy จัดกลุ่มข้อมูลตาม....
var strQry = SelectedFilter
.GroupBy(x => x.CampusId == "05")
.ToListAsync();

Aggregate function

คำสั่ง ใช้สำหรับ ตัวอย่าง ผลลัพธ์
Count
var strQry = SelectedFilter
.CountAsync(x => x.CampusId == "05");
Sum
var strQry = SelectedFilter
.SumAsync(x => x.CampusId == "05");
Min
var strQry = SelectedFilter
.MinAsync(x => x.CampusId == "05");
Max
var strQry = SelectedFilter
.MaxAsync(x => x.CampusId == "05");
Average
var strQry = SelectedFilter
.AverageAsync(x => x.CampusId == "05");
FirstOrDefault
var strQry = SelectedFilter.FirstOrDefaultAsync();
Contain

คำสั่งในการแปลงกลุ่มข้อมูล

คำสั่ง ใช้สำหรับ ตัวอย่าง ผลลัพธ์
ContToList

ToHashSet

ToArray
var strQry = SelectedFilter
.ToArrayAsync()
ToDictionary
var strQry = SelectedFilter
.ToDictionaryAsync(c => c.Id, c => c);

FirstOrDefaultAsync()

ใช้สำหรับการดึงข้อมูล เป็น

model? คือ ค่านี้มีโอกาสที่เป็น null ได้

model? result = await context.table.FirstOrDefaultAsync();

ToListAsync()

List<model> result = await context.table.ToListAsync()

ToArrayAsync()

SalaryStatus[] result = await context.table.ToArrayAsync()

Where()

สามารถเขียนได้หลาย Where() ซึ่ง Where() จะเท่าเท่ากับ And ใน sql

model? result = await context.table
    .Where(c => c.Id == 1)
    .Where(c => c.name == "นายก")
    .ToListAsync()

Contains()

ค้นหาคำโดยการใช้ keyword ในการค้นหา

public async Task<List<model>> ContainsFunction(string keyword){
    List<model> result = await context.table
        .Where(c => c.fullName.Contains(keyword))
        .ToArrayAsync();
}

Distinct() DistinctBy()

Distinct() จะตัดตัวซ้ำทั้ง table

List<model> result = await context.table
    .Distinct()
    .ToArrayAsync();

DistinctBy() จะตัดตัวซ้ำเฉพาะ field ที่เลือก

List<model> result = await context.table
    .DistinctBy(c => c.name == "dev")
    .ToArrayAsync();

IQueryable

ใช้ในการดึงข้อมูลที่มีปริมาณมาก เช่น การค้นหาข้อมูลต่างๆ ไม่ว่าจะเป็นการค้นหารายชื่อ น.ศ วิทยาเขต หรือรายชื่อบุคลากร ในวิทยาเขตเป็นต้น

private IEnumerable<object> LoadAllFiles(int skip, int take, string fileRevision, string fileNumber)
{
    using (var context = new LINQEntities())
    {
        //Select and perform join on the needed tables and build an IQueryable collection
        IQueryable<FileRepository> fileCollection = context.FileRepository;

        //Build queries dynamically over Queryable collection
        if(!string.IsNullOrEmpty(fileRevision))
       fileCollection = fileCollection.Where(a => a.FileRevision == fileRevision && a.IsDeleted == false);

        //Build queries dynamically over Queryable collection
        if (!string.IsNullOrEmpty(fileNumber))
       fileCollection = fileCollection.Where(a => a.FileRevision == fileNumber && a.IsDeleted == false);

        //Apply skip and take and load records
        return fileCollection.OrderBy(a=>a.Id).Skip(()=>skip).Take(()=>take).Select(a=>new
        {
            FileIssuedBy=a.FileIssuedBy
        }).ToList();
    }
}

skip() take()

ข้อควรระวัง

var skip = 0;
var take = 10;
List<model> result = await context.table
    .Skip(skip)
    .Take(take)
    .ToListAsync();

แนะนำให้ใช้

var skip = 0;
var take = 10;
List<model> result = await context.table
    .Skip(()=>skip)
    .Take(()=>take)
    .ToListAsync();

OrderBy() ThenBy()

OrderBy() คือการเรียงลำดับ จากน้อยไปมาก A-Z (ASC)

ThenBy ใช้กรณีที่มีการ OrderBy มากกว่า 1 ตัว

List<model> result = await context.table
    .OrderBy(a => a.Id)
    .ThenBy(a => a.name)
    .ToListAsync();

OrderByDescending() ThenByDescending()

OrderByDescending() คือการเรียงลำดับ จากมากไปน้อย Z-A (DESC)

ThenByDescending ใช้กรณีที่มีการ OrderByDescending มากกว่า 1 ตัว

List<model> result = await context.table
    .OrderByDescending(a => a.Id)
    .ThenByDescending(a => a.name)
    .ToListAsync();

ToDictionaryAsync()

Dictionary

[int] คือ id ในการ map การใช้งาน

[model] คือ ค่าที่ได้จากการ map

Dictionary<int, model> result =  await context.table.ToDictionaryAsync(c => c.id, c => c);

/// การเรียกใช้งาน
model data = result[1];
string name = data.name; // or (result[1]).name

AsNoTracking()

การใช้งานแนะนำให้ใช้กับ การดึงข้อมูลที่มาจาก Table View

ข้อควรระวัง หากมีการประกาศใน Table คือ data ที่ได้มาจะไม่มีการ Tracking Data จาก Table กลับมา [จะไม่สามารถนำ Data ที่ได้มาไป Updat เข้าฐานข้อมูลได้โดยตรง]

model? result = await context.viewTable
    .Where(c => c.id == 1)
    .AsNoTracking()
    .FirstOrDefaultAsync();

Select

กรณีต้องการใช้ข้อมูลบ้าง column แนะนำให้เยกเฉพาะ column ที่ต้องการเท่านั้น

List<string?> result = await context.table
    .select(x => x.CampusId)
    .ToListAsync()

เลือกข้อมูลที่จะใช้งานโดยที่สร้าง model ใหม่มารับค่า

// public class SelectedFilter{
//     public string? CampusId { get; set; }
//     public string? CFacultyId { get; set; }
//     public string? CDeptId { get; set; }
//     public string? CSectionId { get; set; }
// }

List<SelectedFilter> result = await context.table
    .select(x => new SelectedFilter(){
        CampusId = x.CampusId,
        CFacultyId = x.CFacultyId,
        CDeptId = x.CDeptId,
        CSectionId = x.CSectionId,
    })
    .ToListAsync()

Aggregate function

SumAsync

int result = await context.table.SumAsync(x => x.score);

MaxAsync

int result = await context.table.MaxAsync(x => x.score);

MinAsync

int result = await context.table.MinAsync(x => x.score);

AverageAsync

int result = await context.table.AverageAsync(c => c.score);

การใช้คำสั่ง join

var result = await product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
    .Select(m => new {
        ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
        CatId = m.c.CatId
        // other assignments
    })
    .ToListAsync()