我需要在运行时使用Entity Framework进行连接和架构更改。
我尝试了以下代码:Post
我正在使用该代码:
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不会生成带有连接参数的实体构造函数。
感谢您的帮助。这让我发疯了......