2015年9月8日 星期二

執行非同步作業 - Entity Framework

Tool:Visual Studio 2013 Ultimate Update 4 、Entity Framework 6.1.1 tools for visual studio 2013
OS:Windows 8.1
DB:EntityFramework 6.1.3

Entity Framework 6支援 async/await pattern,方便開發非同步作業。我們可以利用Entity Framework所提供的 async結尾的方法,來進行非同步操作。

以下範例以非同步方式新增兩筆資料到資料庫 :

public async static void CreateDataAsync( ) {

  using ( OperaContext context = new OperaContext( ) ) {

    context.Operas.Add( new Opera( ) {
      Title = "Cosi Fan Tutte"
    } );
    context.Operas.Add( new Opera( ) {
      Title = "Carmen"
    } );
    await context.SaveChangesAsync( );

    Console.WriteLine( "Create data complete !" );
  }
}

以下範例使用非同步方式查詢資料

public async static void ListDataAsync( ) {
  using ( OperaContext context = new OperaContext( ) ) {
    var result = await context.Operas.ToListAsync( );
    Console.WriteLine( "List of Data :");
    foreach ( var item in result ) {
      Console.WriteLine( item.OperaID.ToString() + "," + item.Title);
    }
  }

}

完整程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Common;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace ConsoleApplication4 {
  public class Program {
    static void Main( string[ ] args ) {
      CreateDataAsync( );
      ListDataAsync( );
      Console.WriteLine( "完成!" );
      Console.ReadLine( );
    }

    public async static void CreateDataAsync( ) {

      using ( OperaContext context = new OperaContext( ) ) {

        context.Operas.Add( new Opera( ) {
          Title = "Cosi Fan Tutte"
        } );
        context.Operas.Add( new Opera( ) {
          Title = "Carmen"
        } );
        await context.SaveChangesAsync( );

        Console.WriteLine( "Create data complete !" );
      }
    }

    public async static void ListDataAsync( ) {
      using ( OperaContext context = new OperaContext( ) ) {
        var result = await context.Operas.ToListAsync( );
        Console.WriteLine( "List of Data :" );
        foreach ( var item in result ) {
          Console.WriteLine( item.OperaID.ToString( ) + "," + item.Title );
        }
      }

    }
  }
  public class OperaContext : DbContext {
    public DbSet<Opera> Operas { get; set; }
  }
  public class Opera {
    public int OperaID { get; set; }
    public string Title { get; set; }

  }
}

範例執行結果 :

image

沒有留言:

總瀏覽量