DbContext类的IDbSet属性的适配器模式 [英] Adapter pattern for IDbSet properties of a DbContext class

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

问题描述

有没有办法使用此答案中描述的方法 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方法的支持。我理解Keith Payne写的所有内容,但我不知道如何在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
}

现在,您可以在需要它并获取IAsyncDbSet时创建一个 DbSetAdapater
您可以复制您的属性,因为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属性的适配器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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