将System.Type传递给泛型类型

问题描述 投票:0回答:1

我的问题是这个A有一个API控制器并且创建一个Single方法删除来自X DbSet属性的数据但是没有相同的Generic参数。我的结果是以某种方式将System.Type传递给Generic paramether。我的问题是一些方法吗?

    var table = TableInfo.GetValue(_context) as DbSet<[here i need pass it]>;

我需要做一些事情(我知道这不行)

    var table = TableInfo.GetValue(_context) as DbSet<TableInfo.GetType>;

我的完整代码

    [HttpDelete("{name}/{id}")]
    [Route("api/Delete")]
    public IActionResult Delete(string name = "Items", int id = 2)
    {
        PropertyInfo TableInfo = GetValueByName(name);
        if (TableInfo == null)
            return NotFound("Haaaah");

        var table = TableInfo.GetValue(_context) as DbSet<[here i need pass it]>;
        if (table == null)
            return BadRequest();

        var prop = table.SingleOrDefault(p => p.Id == id);
        if (prop == null)
            return NotFound(prop);

        table.Remove(prop);
        _context.SaveChanges();
        return Ok();
    }

    public PropertyInfo GetValueByName(string name)
    {
        Type t = _context.GetType();
        List<PropertyInfo> list = new List<PropertyInfo>(t.GetProperties());
        foreach(PropertyInfo m in list)
        {
            if (m.Name == name)
                return m;
        }
        return null;
    }

最后抱歉我的英语。并感谢所有的答案:)

c# asp.net generic-type-argument system.type
1个回答
0
投票

var table = TableInfo.GetValue(_context) as DbSet<[here i need pass it]>;

你不能这样做,你没有关于你需要什么类型的编译时间信息,你希望在代码运行之前如何利用它?

如果你真的想要table的编译时类型信息,你要么在编译时知道泛型类型,要么考虑到你的方法必须处理的所有潜在泛型类型(可怕的,不要这样做)。

使用界面也不起作用。一个假设的IIdEntity和沿table as DbSet<IIdEntity>线的演员将永远不会工作,因为:

  1. 类型差异仅在接口和委托中允许,DbSet不是接口。
  2. 即使您使用IDbSet<TEntity>,此接口在TEntity中也是不变的,因此以下内容将始终失败: class User: IIdEntity { ... } object o = someDbEntityOfUser; var db = o as IDbSet<IIdEntity> //will always be null.

您当前设置的最佳选择是:

  1. 继续使用反射;用它来检查实体的Id属性。
  2. 使用dynamic并让运行时解析Id调用。
© www.soinside.com 2019 - 2024. All rights reserved.