如何在运行时更改 LINQ O/R-M 表名/源?
- 作者: 青菜馒头丝
- 来源: 51数据库
- 2022-12-13
问题描述
我有一个数据库和一个由 O/R-Mapper 创建的实体集,所有这些都与 LINQ 一起使用.
I've got a database, and an entityset created by the O/R-Mapper, using all this with LINQ.
在 O/R-Mapper 中,我需要为每个表输入一个表名(源),用于 LINQ 生成的 SQL.在 .dbml 文件中,它看起来像这样:
In the O/R-Mapper I need to enter a table name (source) for every table, which is being used for the SQL generated by LINQ. In the .dbml file it looks like this:
<Table Name="dbo.Customers" Member="Customers">
现在我想在运行时更改这个表名,所以 SQL 将针对其他一些表(例如,customers2008 而不是 customer)运行.
Now I'd like to change this table name during runtime, so the SQL will be run against some other table (customers2008 instead of customer, for example).
有没有办法在运行时更改表名(源名)?
Is there any way to change the table name (source name) during runtime?
[更新] 经过一些令我沮丧的测试后,我不得不发现 XmlMappingSource 确实将未保留在数据库中的计算属性呈现为不可访问(是的,即使由 SqlMetal 创建的映射也忽略了所有未保留的内容).>
[Update] After some testing to my dismay I had to discover that XmlMappingSource does render computed properties which are not persisted in the database unaccessable (yes, even the mapping created by SqlMetal does ignore everything which is not persisted).
推荐答案
有点……你必须做这样的事情:
Kind of ... You'd have to do something like this:
- 在设计器中创建实体.
- 使用 SqlMetal 从设计器生成的 .dbml 文件生成 xml 映射文件.
- 更新 xml 文件中的表名.
- 然后在您的代码中,使用接受使用 xml 映射文件创建的 XmlMappingSource 的 DataContext 构造函数重载.
这是一篇博客文章,一步一步解释了这个过程:http://weblogs.asp.net/guybarrette/archive/2008/07/23/linq-to-sql-dynamic-mapping.aspx
Here's a blog post that explains this process step by step: http://weblogs.asp.net/guybarrette/archive/2008/07/23/linq-to-sql-dynamic-mapping.aspx
我对 ERP 数据库使用了类似的过程,该数据库的表名类似于 ttccom001xxx,其中 xxx 是安装 ID(我知道这是一个可怕的架构,但我对此无能为力).我们有多个安装,因此我为每个安装复制一次初始 xml 映射,然后将 xxx 替换为安装 ID.我编写了一个使用 Regex 处理替换的小型控制台应用程序,并将其添加到我的构建过程中.
I'm using a similar process with an ERP database that has table names like ttccom001xxx where xxx is the installation ID (I know it's a horrible schema, but there's nothing I can do about it). We have multiple installations, so I copy the initial xml mapping once for each installation and then replace xxx with the installation ID. I wrote a small console app that uses Regex to take care the replacements and added it as part of my build process.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
