gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:47:09 25 4
gpt4 key购买 nike

(这曾经是一个由两部分组成的问题,但由于第二部分确实很重要,所以我决定将其分成两个单独的帖子。请参阅 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com