如何处理动态表名
How to process dynamic tablenames
我有许多 table 需要使用 Linq
组合成一个结构
我需要处理许多具有相同结构但 table 名称不同的 table(财务数据跨越 20 年)。我可以创建代码来动态访问各种 table 内容:
string tableName = "Trading.DataSources.Prices2017";
var results = DbContext.Set(Type.GetType(tableName));
但是,当我尝试使用 Cast 将一个 table 的结果转换为一个普通的 table(具有相同 table 结构的价格)时:
var newResults = results.AsQueryable().Cast<Price>().ToList();
我收到以下错误:
"System.NotSupportedException: 'Unable to cast the type 'Trading.DataSources.Prices2017' to type 'Trading.DataSources.Price'. LINQ to Entities only supports casting EDM primitive or enumeration types.'"
我显然可以用我自己的转换方法进行这种转换。然而,这会导致同一代码块的多个版本以满足不同的 tables 并且每年,当我有一组新的价格数据时,我必须修改我的代码以适应新的一年table姓名。
有没有办法动态地(或一般地)处理这个问题?
制作新模型classSharedPrices
。此 class 将包含这些表具有的所有相同值
var newResults = results.select(r => new SharedPrices{value1 = r.value1, value2 = r.value2}).ToList();
对于我的示例,所有价格表只有:
- 值 1
- 值2
这些应该代替您实际的 class 结构。
我为你做了更多的挖掘,我想感谢@Tyler-Long 的回答here。
他的回答基本上指出,您可以使用 JSON (反)序列化来将 class 反映到另一个中,而无需编写演员表,只要它们具有 exact 相同的属性,像这样:
using Newtonsoft.Json;
string tableName = "Trading.DataSources.Prices2017";
var tableType = Type.GetType(tableName);
var results = DbContext.Set(tableType);
Price newResults = JsonConvert.DeserializeObject<tableType>(JsonConvert.SerializeObject(results.ToList()));
我认为这将使您能够将表格转换为单一价格模型,而无需显式编写转换逻辑。唯一的缺点是它为您的项目添加了对 Newtonsoft.json 包的依赖(可以通过 nuget 下拉)。不过这个包我个人用过,值得信赖。
我有许多 table 需要使用 Linq
组合成一个结构我需要处理许多具有相同结构但 table 名称不同的 table(财务数据跨越 20 年)。我可以创建代码来动态访问各种 table 内容:
string tableName = "Trading.DataSources.Prices2017";
var results = DbContext.Set(Type.GetType(tableName));
但是,当我尝试使用 Cast 将一个 table 的结果转换为一个普通的 table(具有相同 table 结构的价格)时:
var newResults = results.AsQueryable().Cast<Price>().ToList();
我收到以下错误:
"System.NotSupportedException: 'Unable to cast the type 'Trading.DataSources.Prices2017' to type 'Trading.DataSources.Price'. LINQ to Entities only supports casting EDM primitive or enumeration types.'"
我显然可以用我自己的转换方法进行这种转换。然而,这会导致同一代码块的多个版本以满足不同的 tables 并且每年,当我有一组新的价格数据时,我必须修改我的代码以适应新的一年table姓名。
有没有办法动态地(或一般地)处理这个问题?
制作新模型classSharedPrices
。此 class 将包含这些表具有的所有相同值
var newResults = results.select(r => new SharedPrices{value1 = r.value1, value2 = r.value2}).ToList();
对于我的示例,所有价格表只有:
- 值 1
- 值2
这些应该代替您实际的 class 结构。
我为你做了更多的挖掘,我想感谢@Tyler-Long 的回答here。 他的回答基本上指出,您可以使用 JSON (反)序列化来将 class 反映到另一个中,而无需编写演员表,只要它们具有 exact 相同的属性,像这样:
using Newtonsoft.Json;
string tableName = "Trading.DataSources.Prices2017";
var tableType = Type.GetType(tableName);
var results = DbContext.Set(tableType);
Price newResults = JsonConvert.DeserializeObject<tableType>(JsonConvert.SerializeObject(results.ToList()));
我认为这将使您能够将表格转换为单一价格模型,而无需显式编写转换逻辑。唯一的缺点是它为您的项目添加了对 Newtonsoft.json 包的依赖(可以通过 nuget 下拉)。不过这个包我个人用过,值得信赖。