一类的DbContext的IDbSet性能Adapter模式 [英] Adapter pattern for IDbSet properties of a DbContext class

查看:444
本文介绍了一类的DbContext的IDbSet性能Adapter模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有使用这个答案没有对IDbSet FindAsync()方法了解的DbSet性能的方法的一种方式一个的DbContext?

Is there a way to use the method described in this answer No FindAsync() method on IDbSet for DbSet properties of a DbContext?

编辑:

链接答案包含了描述如何建立一个接口从IDbSet继承和增加对DbSet类的SearchAsync方法的支持。我明白这基思·佩恩写了一切,但我不知道我怎么能在的DbContext使用它。

The answer linked contains a description how to build a interface inheriting from IDbSet and adding support for the SearchAsync method of the DbSet class. I understand everything which Keith Payne has written, but I don’t know how I can use it in DbContext.

例如我有一个的DbContext它看起来是这样的

For example I’ve a DbContext which looks something like this:

public class MyContext : DbContext
{ 
    public DbSet<Customer> Customers { get; set; }
}



我如何使用MyDbSet(类的答案说明。)或类似的类,而不是DbSet,

How can I use MyDbSet (class described in the answer.) or a similar class, instead of DbSet?

public class MyContext : DbContext
{ 
    public MyDbSet<Customer> Customers { get; set; }
}



现在的问题,是实体框架似乎只生成的属性表类型IDbSet或DbSet。

The problem is now, that Entity Framework seem to generate only tables for properties of type IDbSet or DbSet.

推荐答案

您对您的上下文有定期DbSet并创建一个适配器添加请求的接口。

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
}

现在,您可以创建一个 DbSetAdapater 当你需要它,并得到一个IAsyncDbSet。
你可以复制你的属性EF似乎忽略它们或添加 ToAsyncDbSet()扩展方法 IDbSet< T>

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

这篇关于一类的DbContext的IDbSet性能Adapter模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆