我在 C# 中有这个函数:
using (SKContext db = new SKContext())
{
dynamic dynamic = new ExpandoObject();
if (category == "Categories")
{
dynamic = db.Categories
.Where(X => X.Active == true)
.Select(f => f.Name).ToList();
}
else if (category == "Brands")
{
dynamic = db.Brands
.Where(X => X.Active == true)
.Select(f => f.Name).ToList();
}
else if (category == "Characters")
{
dynamic = db.Characters
.Where(X => X.Active == true)
.Select(f => f.Name).ToList();
}
return dynamic;
}
我想通过这样的字符串动态选择一个表:
var tableName = "Brands";
return db.[tableName].Where(X => X.Active == true).Select(f => f.Name).ToList();
有人可以帮忙吗?
答案 0 :(得分:0)
我建议引入一些鉴别器类型/接口并在那里声明通用属性/功能,而不是动态化:
public interface ISomeInterface
{
bool Active { get; set; }
string Name { get; set; }
}
public class Category : ISomeInterface {...} // and others
并使用此接口构建查询:
IQueryable<ISomeInterface> query = category switch
{
"Categories" => db.Categories,
// ...
_ => throw new ArgumentOutOfRangeException()
};
return query.Where(X => X.Active == true).Select(f => f.Name).ToList();