简体   繁体   English

实体框架DbContext与不同的数据库兼容

[英]Entity Framework DbContext compatible with different databases

Using Entity Framework, I have created an application which is able to read data from the database it was modeled against. 使用实体框架,我创建了一个应用程序,该应用程序能够从其建模所依据的数据库中读取数据。 I now have another database, with the same tables, hosted on another server. 现在,我在另一个服务器上托管了另一个具有相同表的数据库。

The problem is that the tables on the second database belong to a schema with a different name to the original, so simply changing the connection string for my context in the app.config file doesn't work. 问题在于第二个数据库上的表属于与原始名称不同的架构,因此仅更改app.config文件中上下文的连接字符串不起作用。 (I get the error "table or view does not exist"). (我收到错误“表或视图不存在”)。 There must be some mapping somewhere in the auto generated code stating the original schema name. 自动生成的代码中一定有一些映射说明原始模式名称。

What is the correct way to handle this kind of situation? 处理这种情况的正确方法是什么? I don't really want to have to re-model the second database as it is identical to the first. 我真的不需要重新建模第二个数据库,因为它与第一个数据库相同。 I can't change the databases as other applications would stop working. 我无法更改数据库,因为其他应用程序将停止工作。

Any nudge in the right direction would be greatly appreciated. 任何朝着正确方向前进的人将不胜感激。

OK, so here's what I've done to solve this. 好的,这就是我为解决此问题所做的工作。

As @Kelmen mentioned in the comments, opening the EDMX file in a text editor revealed that this is where the schema information is stored. 正如@Kelmen在评论中提到的那样,在文本编辑器中打开EDMX文件显示这是存储模式信息的位置。 So I think I could have simply cleared out the value of the schema attribute and used the connection string to drive the schema. 所以我想我可以简单地清除schema属性的值,并使用连接字符串来驱动schema。

This didn't feel right for a couple of reasons: 由于以下几个原因,这种感觉不正确:

  1. If the model was refreshed at any point, it might have repopulated the schema names, which would be REALLY annoying. 如果在任何时候刷新了模型,它可能已经重新填充了架构名称,这真是令人讨厌。 I didn't have time to test if this would actually happen. 我没有时间测试这是否真的会发生。

  2. This method wouldn't let me control the schema name if I did need to change it at runtime. 如果确实需要在运行时进行更改,则该方法将不允许我控制模式名称。

The solution was to use Code First and the Fluent API to edit the model configuration in the OnModelCreating event within my derived DbContext class. 解决方案是使用代码优先和Fluent API在派生的DbContext类中的OnModelCreating事件中编辑模型配置。

I'm now considering modifying my context class so that I can pass in the name of the schema or possibly drive it from my app.config. 我现在正在考虑修改上下文类,以便可以传递架构名称或可能从我的app.config驱动它。

I found the links tutorials to be quite useful: 我发现链接教程非常有用:

Change Schema of Entity Framework 实体框架的变更架构

Entity Framework Change Schema Name Per Connection 每个连接的实体框架更改架构名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM