【问题标题】:Implementing Generic Repository Pattern - entity key type实现通用存储库模式 - 实体键类型
【发布时间】:2017-08-26 20:12:17
【问题描述】:

我正在 Asp.Net web api 应用程序中实现存储库模式。

public abstract class Repository<T> : IRepository<T> where T : EntityBase
 {
     private DbContext context_;

     public Repository(DbContext context)
     {
         context_ = context;
     }

     public virtual async Task<T> GetAsync(int id)
     {
         return await context_.Set<T>().FindAsync(id);
     }

     ...

 }

问题:

这里我有一个方法GetAsync(int id),它适用于具有int 类型的单个键的实体。

但是有些实体的键是string 类型,有些实体是复合键。

问题:

我该如何解决这个问题?

是否有可能以通用的方式解决这个问题?

【问题讨论】:

    标签: c# entity-framework generics asp.net-web-api2 repository-pattern


    【解决方案1】:

    您会注意到FindAsync 接受对象数组作为参数,因此您可以像这样更改您的GetAsync

    public virtual Task<T> GetAsync(params object[] keys)
    {
         return context_.Set<T>().FindAsync(keys);
    }
    

    然后你就可以使用任何你喜欢的键调用GetAsync,例如:

    GetAsync(1);
    GetAsync("string key");
    GetAsync(1, "composite key");
    

    附注:实体框架Set&lt;T&gt; 已经是通用存储库,因此在该存储库上添加另一个存储库并不会真正增加太多好处。

    【讨论】:

    • 谢谢!我没注意到params object[] keys
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多