使用(var db = new MyApp Context)从 entity framework 中的函数中删除样板

Remove boiler plate using(var db = new MyAppContext) from functions in entity framework

在使用 entity framework 时,将数据函数包装在 using 语句中是一种标准做法。例如

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

通常里面只有一个return语句。有没有办法做到这一点,而不必每次都编写 using 语句。使用新的 c# 功能,函数将更易于编写。

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

我有很多方法可以像那样使用这个 using 块,如果有办法不用它,它会使代码更简单。

提前致谢。

我不能说我完全赞同你想要的,但是,下面的代码:

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();
        }
    }
}

或者,您可以在 using 中换行,这具有完全相同的效果并且可能更简洁:

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());

为了完整起见,下面是我用来测试此功能的示例 class:

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

    public int SomeMethod() => 1;
}