我可以在ASP.NET Core中创建一个像Laravel Resource 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张表中做简单的碎屑。所有操作都是相同的,例如Get((用于从该模型中获取所有数据。

我只想写一次并将其扩展到每个模型控制器。

,而不是写3次。

任何想法如何做?

c#不允许您在这样的运行时撰写表达式。

但是,EF有一个API。
您正在寻找.Set<T>()

如果要使用实体框架执行简单的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<,>));

最新更新