我可以在ASP.NET Core中创建一个类似Laravel资源控制器的控制器吗?

时间:2019-06-24 17:18:00

标签: c# rest api controller

因此,例如,我有这样的Laravel资源控制器代码:

class BaseAPIController extends Controller
{
    public function index()
    {
        return self::$model->all();
    }
}

因此,我试图在ASP.NET C#中做到这一点:

[ApiController]
public class BaseAPIController<T> : ControllerBase
{
    [HttpGet]
    public ActionResult<IEnumerable<T>> Get()
    {
        using (ExamRTContext db = new ExamRTContext())
        {
            return db.${typeof(T).Name}.Select(x => x);
        }
    }
}

但是我不知道该怎么做。

因此,假设我只是想在3个表中进行简单的CRUD。所有操作都是相同的,例如Get()用于从该模型获取所有数据。

我不想编写3次,而是只编写一次并将其扩展到每个模型控制器。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

C#不允许您在运行时这样编写表达式。

但是,EF具有执行此操作的API。
您正在寻找.Set<T>()

答案 1 :(得分:0)

如果要使用实体框架执行简单的CRUD操作,则可以创建一个通用存储库。

存储库:

    public class GenericRepository<TEntity, TContext>
        where TContext : DbContext
        where TEntity : class
    {
        protected readonly TContext context;

        public GenericRepository(TContext context)
        {
            this.context = context;
        }

        public virtual async Task Add(TEntity model)
        {
            await context.Set<TEntity>().AddAsync(model);
            await context.SaveChangesAsync();
        }

        public virtual async Task<TEntity> Get(int id)
        {
            return await context.Set<TEntity>().FindAsync(id);
        }

        public virtual async Task<IEnumerable<TEntity>> GetAll()
        {
            return await context.Set<TEntity>().ToListAsync();
        }

        public virtual async Task<TEntity> FindFirstBy(Func<TEntity,bool> predicate)
        {
            return await Task.Run(()=> context.Set<TEntity>().FirstOrDefault(predicate));
        }

        public virtual async Task<IEnumerable<TEntity>> FilterBy(Func<TEntity,bool> predicate)
        {
            return await Task.Run(()=> context.Set<TEntity>().Where(predicate).ToList());
        }

        public virtual async Task Update()
        {
            await context.SaveChangesAsync();
        }

        public virtual async Task Remove(TEntity model)
        {
            context.Set<TEntity>().Remove(model);
            await context.SaveChangesAsync();
        }
    }

要使用它,只需将其注入到指定实体类型和上下文的控制器中。在您的示例中,它就像:

控制器库:

[ApiController]
public class BaseAPIController<T> : ControllerBase
{
    protected readonly GenericReposoitory<T,ExamRTContext> repository;

    public BaseAPIController(GenericRepository<T,ExamRTContext> repository) {
        this.repository = repository;
    }

    [HttpGet]
    public ActionResult<IEnumerable<T>> Get()
    {
        var entities = repository.GetAll();
        if (entities!= null) {
            return Ok(entities);
        }
        return NotFound();
    }
}

在启动中:

services.AddTransient(typeof(GenericRepository<,>), typeof(GenericRepository<,>));