Entity Framework入門教程(11)---EF6中的異步查詢和異步保存


EF6中的異步查詢和異步保存

在.NET4.5中介紹了異步操作,異步操作在EF中也很有用,在EF6中我們可以使用DbContext的實例進行異步查詢和異步保存。

1.異步查詢

下邊是一個通過L2E語法實現異步查詢的栗子:

private static async Task<Student> GetStudent()
{
    Student student = null;

    using (var context = new SchoolDBEntities())
    {
        Console.WriteLine("Start GetStudent...");
         //注意await和FirstOrDefaultAsync
        student = await (context.Students.Where(s => s.StudentID == 1).FirstOrDefaultAsync<Student>());
            
        Console.WriteLine("Finished GetStudent...");
    }
    return student;
}

上邊的栗子中,GetStudent()方法使用async關鍵字修飾后就表示它是一個異步方法,異步方法的返回類型必須是Task<T>類型,因為GetStudent()方法要返回一個Student實體,所以返回的類型是Task<Student>。

同樣的,Linq表達式使用await關鍵字修飾,await表示讓當前線程去執行其他代碼,直到linq表達式執行結束並返回結果。我們使用FirstOrDefaultAsync異步擴展方法來獲取結果,我們也可以使用其他的異步擴展方法如SingleOrDefautAsync,ToListAsync等。

2.異步保存

EF API提供了SaveChangesAsync()方法來異步地把數據保存到數據庫,下邊栗子中的SaveStudent方法異步的將Student實體保存到數據庫。

private static async Task SaveStudent(Student editedStudent)
{
    using (var context = new SchoolDBEntities())
    {
        context.Entry(editedStudent).State = EntityState.Modified;
                
        Console.WriteLine("Start SaveStudent...");
                
        int x = await (context.SaveChangesAsync());
                
        Console.WriteLine("Finished SaveStudent...");
    }
}

3.一個查詢,獲取結果,保存的栗子

public static void AsyncQueryAndSave()
{
    var query = GetStudent();
            
    Console.WriteLine("Do something else here till we get the query result..");

    query.Wait();

    var student = query.Result;
    
    student.FirstName = "Steve";
    //上邊的SaveStudent方法        
    var numOfSavedStudent = SaveStudent(student);
            
    Console.WriteLine("Do something else here till we save a student.." );

    studentSave.Wait();

    Console.WriteLine("Saved Entities: {0}", numOfSavedStudent.Result);
}

執行的結果如下所示:

Start GetStudent... 
Do something else here till we get the query result..
Finished GetStudent...
Start SaveStudent...
Do something else here till we save a student..
Finished SaveStudent...
Saved Entities: 1

在上邊的栗子中。首先調用GetStudent()方法時,把任務存儲在query變量中,執行到await表達式的時候,當前線程被釋放,去執行調用方法(AsyncQueryAndSave方法)中的代碼,執行到query.wait()時,停止線程執行直到GetStudent()徹底執行完成。一旦GetStudent()執行完成,我們可以通過query.Result獲取查詢到的Student實例。SaveStudent()也是一樣的執行過程。關於異步可以參考以前總結的一篇文章

 

EF系列目錄鏈接:Entity Franmework系列教程匯總


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM