简体   繁体   English

用于数据库词典的ASP.NET通用控制器(使用实体框架)

[英]ASP.NET universal controller for database dictionaries (using Entity Framework)

I've got some models that only have two fields: Id and Name. 我有一些只有两个字段的模型:Id和Name。 All this models inherit from IDbDictionary interface. 所有这些模型都继承自IDbDictionary接口。

My goal is to make "universal" controller for CRUD operations for this models. 我的目标是为该模型的CRUD操作制作“通用”控制器。 My problem is how to (using EF) modify database table by name. 我的问题是如何(使用EF)按名称修改数据库表。 For example, there is method 例如有方法

    [HttpPost]
    public ActionResult Create(IDbDictionary newRecord, string collectionName)
    {
        if (ModelState.IsValid)
        {
            db.<collectionName>.Add(newRecord);
            db.SaveChanges();
            return View("Success");
        }

        return View("Create", newRecord);
    }

Is there a way to do it the way I described? 有没有办法按照我描述的方式来做? I thought about reflection, but I've no idea how to do this. 我考虑过反射,但是我不知道该怎么做。

Regards, 问候,
C C

Usually you would have a Service that would handle your generic database operations which you can call from all your methods. 通常,您将拥有一个可以处理通用数据库操作的服务,您可以从所有方法中调用该Service Example: 例:

public class DataService
{
    public readonly ApplicationDbContext dbContext;

    public DataService(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public void Create<TEntity>(TEntity entity) where TEntity : IDbDictionary 
    {
        this.dbContext.Set<TEntity>().Add(entity);
        this.dbContext.SaveChanges();
    }
}

Then in your method you would use: 然后在您的方法中使用:

var dataService = new DataService(this.dbContext);
dataService.Create<ClassName>(newEntity);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM