我正在尝试为MVC 6应用程序制作一个通用的表格查看器/编辑器。
目前我使用
Context.GetEntityTypes();
返回一个表格列表。
现在我需要获取特定类型的数据。我的当前实现是:
// On my context
public IQueryable<dynamic> GetDbSetByType(string fullname)
{
Type targetType = Type.GetType(fullname);
var model = GetType()
.GetRuntimeProperties()
.Where(o =>
o.PropertyType.IsGenericType &&
o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
o.PropertyType.GenericTypeArguments.Contains(targetType))
.FirstOrDefault();
if (null != model)
{
return (IQueryable<dynamic>)model.GetValue(this);
}
return null;
}
使用这段代码在我的控制器中
[HttpGet("{requestedContext}/{requestedTable}/data")]
public IActionResult GetTableData(string requestedContext, string requestedTable)
{
var data = Request.Query;
var context = GetContext(requestedContext);
if (context == null)
{
return new ErrorObjectResult("Invalid context specified");
}
var entity = context.GetEntity(requestedTable);
if (entity == null)
{
return new ErrorObjectResult("Invalid table specified");
}
var set = context.GetDbSetByType(entity.ClrType.AssemblyQualifiedName);
if (set == null)
{
return new ErrorObjectResult("Invalid table specified - DbSet could not be found");
}
var start = Convert.ToInt32(data["start"].ToString());
var count = Convert.ToInt32(data["length"].ToString());
var search = data["search[value]"];
return new ObjectResult(set.Skip(start).Take(count));
}
目前情况下,这将返回长度为 count
且从位置 start
开始的数据。但是我无法对 IQueryable<dynamic>
特定属性执行查询。问题在于:
- 这似乎是一件微不足道的事情,所以我几乎确定我错过了什么 - 这应该很容易做到。
- 如果不是1,则如何将我的
object set
转换回DbSet<T>
,以便我可以执行我的查询?如果我设置断点并检查,我可以看到所有的数据都在那里。
requestedTable
是完全限定类型,例如:<mysystem>.Models.Shared.Users