c# - "Cloning" Entity Framework 中的 EntityConnections 和 ObjectContext

标签 c# .net entity-framework .net-4.5 entity-framework-5

(这曾经是一个由两部分组成的问题,但由于第二部分确实很重要,所以我决定将其分成两个单独的帖子。请参阅 Using Serialization to copy entities between two ObjectContexts in Entity Framework 了解第二部分。

我想为我的实体模型创建一个相当通用的数据库“克隆器”。此外,我可能需要支持不同的提供商等。我正在使用 ObjectContext API。

我知道 this question alreadyEntityConnectionStringBuilder MDSN documentation例如,但我需要知道是否有一种编程方式来获取值以初始化 EntityConnectionStringBuilderProviderMetadata 属性?

using (var sourceContext = new EntityContext()) {
    var sourceConnection = (EntityConnection) sourceContext.Connection;
    var targetConnectionBuilder = new EntityConnectionStringBuilder();

    targetConnectionBuilder.ProviderConnectionString = GetTargetConnectionString();
    targetConnectionBuilder.Provider = "System.Data.SqlClient"; // want code
    targetConnectionBuilder.Metadata = "res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl"; // want code

    using (var targetContext = new EntityContext(targetConnectionBuilder.ConnectionString)) {
        if (!targetContext.DatabaseExists())
            targetContext.CreateDatabase();

        // how to copy all data from the source DB to the target DB???
    }
}

也就是有没有办法获取

  • “System.Data.SqlClient”
  • "res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl"

来自某处而不使用文字值?

最佳答案

元数据

您应该能够使用 res://*/ 告诉 Entity Framework 在调用程序集中搜索所有 .csdl、.ssdl 和 .msl 文件。或者,使用 res://assembly full name here/ 在特定程序集中搜索。请注意,这两种语法都将加载所有找到的文件,直到您在同一个程序集中有多个 .edmx,这会正常工作,从而产生多个 CSDL/SSDL/MSL 文件(.edmx 文件基本上是这三个文件的串联)。更多信息 on MSDN .

如果您想要更多控制,请使用 Assembly.GetManifestResourceNames列出给定程序集中的所有资源,并手动将 .csdl/.ssdl/.msl 资源匹配在一起,然后从这些资源名称手动构建元数据字符串。

供应商

可以在根节点的 Provider 属性中的 SSDL 文件中找到提供程序。获得正确的文件名后,使用 GetManifestResourceStream并将文件读取为 XML。代码应如下所示:

using (var stream = assembly.GetManifestResourceStream("EntityModel.ssdl")) {
  XDocument document = XDocument.Load(stream);
  string provider = document.Root.Attribute("Provider").Value;
}

关于c# - "Cloning" Entity Framework 中的 EntityConnections 和 ObjectContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12589017/

相关文章:

c# - Kinect:AccessViolationException

c# - 在 System.ConsoleKey 值使用完毕后,如何使它无效(或分配另一个值)?

c# - 如何使简单 WCF 服务在 WPF 应用程序中工作?

c# - Entity Framework - 级联删除未在实体模型中设置

c# - 使用线程显示表单

c# - 我的应用程序的 Windows 10 反馈任务

c# - 在 Windows 10 应用程序中使用图像更新辅助图 block

c# - DataReader 不返回任何行——行存在于数据库中

entity-framework - 添加实体模型时出现错误 3007

.net - 无法使用ADO.NET Entity Framework 执行存储过程