2015-08-28 41 views
1

在使用實體框架時將數據函數包裝在使用語句中是一種標準做法。例如從實體框架中的函數中使用(var db = new MyAppContext)去除鍋爐板

using(var db = new MyAppContext()) 
{ 
    return db.Books.ToList(); 
} 

通常裏面只有一個返回語句。有沒有辦法做到這一點,而不必每次都寫use語句。使用新的c#功能,該功能將更容易編寫。

public IList<Book> GetAllBooks() => db.Books.ToList() 

有很多很多的方法,我有一個使用這種使用塊這樣的,如果有一種方法離不開它,就會使代碼更簡單。

預先感謝您。

+0

可能我問,如果有什麼新的功能C#推出涉及該'公IList GetAllBooks()=> db.Books.ToList()'?它對我來說不是有效的語法。我很晚才更新最新的C#版本。 – Hopeless

+1

這是新的C#6語法。如果你可以嵌入一個lambda,你可以編寫一個輔助函數並執行如下操作:'Books()=> WrapInUsing((Db)=> Db.books));''WrapInUsing'函數調用它的'Action ' ''使用'裏面的參數 –

+1

這是一個[表達體的成員](https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14) – rexcfnghk

回答

0

我不能說我完全同意你想要什麼樣的,但是,下面的代碼:

public static class Extensions 
{ 
    public static TOut DisposeWrapper<TDisposable, TOut>(this TDisposable input, Func<TDisposable,TOut> function) where TDisposable:IDisposable 
    { 
     try 
     { 
      return function(input); 
     } 
     finally 
     { 
      input.Dispose(); 
     } 
    } 
} 

或者,您可以使用,它具有完全相同的效果,也許是包有點更簡潔:

public static class Extensions 
{ 
    public static TOut DisposeWrapper<TDisposable, TOut>(this TDisposable input, Func<TDisposable,TOut> function) where TDisposable:IDisposable 
    { 
     using (input) return function(input); 
    } 
} 

會讓你做類似於你想要的東西。這是稍微詳細的使用,例如:

public static int ExampleUsage() => new Example().DisposeWrapper(x => x.SomeMethod()); 

以及物品是否完整,這裏是我用來測試這個功能的示例類:

public class Example : IDisposable 
{ 
    public void Dispose() 
    { 
     Console.WriteLine("I was disposed of"); 
    } 

    public int SomeMethod() => 1; 
} 
+0

Can你解釋爲什麼你不會批准這個? –

+1

@穆罕默德·伊布拉希姆簡單地指出,簡潔簡潔。就這樣。 – willaien