我需要在运行时使用实体框架进行连接和架构更改。
我尝试了以下代码:发布
我正在使用该代码:
public EntityConnection SetCurrentEntityConnection(string schemaName, string databaseIPAddress, int databasePort, string userName, string password, string model)
{
XmlReader[] MappingReader = new XmlReader[] { XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".msl")) };
XmlReader[] ConceptualReader = new XmlReader[] { XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".csdl")) };
var StorageReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".ssdl"));
XNamespace StorageNS = "http://schemas.microsoft.com/ado/2009/02/edm/ssdl";
var StorageXml = XElement.Load(StorageReader);
foreach (var EntitySet in StorageXml.Descendants(StorageNS + "EntitySet"))
{
var SchemaAttribute = EntitySet.Attributes("Schema").FirstOrDefault();
if (SchemaAttribute != null)
SchemaAttribute.SetValue(schemaName);
}
StorageXml.CreateReader();
var Workspace = new MetadataWorkspace();
StoreItemCollection StorageCollection = new StoreItemCollection(new XmlReader[] { StorageXml.CreateReader() });
EdmItemCollection ConceptualCollection = new EdmItemCollection(ConceptualReader);
StorageMappingItemCollection MappingCollection = new StorageMappingItemCollection(ConceptualCollection, StorageCollection, MappingReader);
Workspace.RegisterItemCollection(ConceptualCollection);
Workspace.RegisterItemCollection(StorageCollection);
Workspace.RegisterItemCollection(MappingCollection);
///
/// Adjust the connection string
///
var ConnectionData = new EntityConnectionStringBuilder();
ConnectionData.Provider = "Oracle.ManagedDataAccess.Client";
ConnectionData.Metadata = "metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
ConnectionData.Name = "Entities";
/// Build the connection string (using Oracle EZ Connection string)
string conn = "data source=" + userName + "/" + password + "@" + databaseIPAddress + ":" + databasePort + "/" + schemaName ;
ConnectionData.ProviderConnectionString = conn;
var Connection = DbProviderFactories.GetFactory(ConnectionData.Provider).CreateConnection();
Connection.ConnectionString = ConnectionData.ProviderConnectionString;
new EntityConnection(Workspace, Connection);
}
我遇到了两个问题:
问题 1:foreach 循环找不到任何 EntitySet 来更改架构。
问题 2:我不知道如何在我的 EF 应用程序中使用新创建的 EntityConnection。我通常使用:
Entity dbContext = new Entity();
并开始对我的 dbContext 进行查询,但我不知道如何处理 EntityConnection 以及应该如何处理它。那么,新创建的 EntityConnection 和原来的 DbContext 之间是什么关系。
顺便说一句,我正在使用 DatabaseFirst for Oracle。DMDX 不会生成带有连接参数的实体构造函数。
谢谢你的帮助。这真让我抓狂...