简体   繁体   English

实现通用存储库模式 - 实体密钥类型

[英]Implementing Generic Repository Pattern - entity key type

I'm implementing a repository pattern in Asp.Net web api application. 我正在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);
     }

     ...

 }

Problem: 问题:

Here I have a method GetAsync(int id) , which will work for entity which has a single key with int type. 这里我有一个方法GetAsync(int id) ,它适用于具有int类型的单个键的实体。

But there are some entity with key of string type and some entities with composite keys. 但是有一些实体具有string类型的键和一些具有复合键的实体。

Question: 题:

How can I overcome this issue? 我怎样才能克服这个问题?

Is it possible to overcome the issue in a generic way? 是否有可能以通用的方式克服这个问题?

You can notice that FindAsync accepts array of objects as a parameter, so you can change your GetAsync like this: 您可以注意到FindAsync接受对象数组作为参数,因此您可以像这样更改GetAsync

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

Then you are able to call GetAsync with any keys you like, for example: 然后,您可以使用您喜欢的任何键调用GetAsync ,例如:

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

Side note: entity framework Set<T> is already generic repository, so adding another repository over that one does not really add much benefits. 附注:实体框架Set<T>已经是通用存储库,因此在该存储库上添加另一个存储库并不会带来太多好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在存储库中实现泛型类型 - Implementing a generic type in repository 实体框架中的通用存储库模式 - Generic Repository Pattern in Entity Framework 带有AutoMapper的通用工作单元和存储库模式引发异常“相同类型的另一个实体已经具有相同的主键值” - Generic UnitofWork & Repository pattern with AutoMapper throwing exception “another entity of the same type already has the same primary key value” 实体框架通用存储库的规范模式 - Specification pattern with Entity Framework generic repository 通用存储库模式和实体框架的问题 - Problems with Generic Repository Pattern and Entity Framework 在通用存储库模式实体框架中删除实体而不获取它 - Remove an entity without fetching it in the generic repository pattern entity framework 基于实体类型的通用存储库应用过滤器 - Generic Repository apply filter based on entity type 通用存储库和实体ID的自定义类型 - Generic repository and custom type of entity Id 使用实体框架为CRUD操作实现通用存储库时出错 - Error on implementing generic Repository for CRUD operations using Entity Framework 首先使用Entity框架代码实现Generic Repository - Implementing Generic Repository using Entity framework code first
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM