我有许多表需要使用 Linq 组合成一个结构
我需要处理一些具有相同结构但表名不同的表(横跨 20 年的财务数据)。我可以创建代码来动态访问各种表格内容:
string tableName = "Trading.DataSources.Prices2017";
var results = DbContext.Set(Type.GetType(tableName));
但是,当我尝试使用 Cast 将一个表中的结果转换为公共(public)表(具有相同表结构的 Price)时:
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.'"
显然,我可以使用自己的转换方法进行转换。然而,这会导致同一代码块的多个版本以满足不同的表格,并且每年,当我有一组新的价格数据时,我必须修改我的代码以适应新的一年的表格名称。
有没有办法动态地(或一般地)处理这个问题?
最佳答案
创建一个新的模型类 SharedPrices
。此类将包含这些表具有的所有相同值
var newResults = results.select(r => new SharedPrices{value1 = r.value1, value2 = r.value2}).ToList();
对于我的示例,所有价格表只有:
- 值1
- 值2
这些应该代替您的实际类结构。
我为您做了更多挖掘,我想感谢@Tyler-Long 的回答 here . 他的回答基本上指出,您可以使用 JSON(反)序列化将一个类反射(reflect)到另一个类中,而无需编写强制转换,只要它们具有完全相同的属性,如下所示:
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 下拉)。不过,我以前亲自使用过这个软件包,它很可靠。
关于c# - 如何处理动态表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55792495/