Adapter pattern for IDbSet properties of a DbContext class

[亡魂溺海] 提交于 2019-12-06 10:20:56

You have regular DbSet on your context and create an adapter adding the requested interface.

public interface IAsyncDbSet<T> : IDbSet<T>
    where T : class
{
    Task<T> FindAsync(params Object[] keyValues);
}

public sealed class DbSetAdapter<T> : IAsyncDbSet<T>, IDbSet<T>
    where T : class
{
    private readonly DbSet<T> _innerDbSet;

    public DbSetAdapter(DbSet<T> innerDbSet)
    {
        _innerDbSet = innerDbSet;
    }

   public Task<T> FindAsync(params object[] keyValues)
   {
          return _innerDbSet.FindAsync(keyValues);
   }

   //Here implement each method so they call _innerDbSet like I did for FindAsync
}

Now you can create a DbSetAdapater when you need it and get an IAsyncDbSet. You could duplicate your properties as EF seems to ignore them or add an ToAsyncDbSet() extension method to IDbSet<T>

public class MyContext : DbContext
{ 
    public DbSet<Customer> Customers { get; set; }
    public IAsyncDbSet<Customer> CustomersAsync { get { return new DbSetAdapter<Customer>(Customers); } }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!