我已使用Code-First Migrations成功创建了一个使用MVC5 / EF6的InventoryTracking应用程序来填充我的LocalDB文件以获取一些测试数据。我现在正在尝试修改应用程序以使用Oracle DB,其中我创建了与我的LocalDB文件中的表相同的表。
经过大量挖掘后,我为VS2013下载了Oracle Developer Tools
(Zip文件:ODTwithODAC121021
)。然后使用NUGET我安装了Oracle.ManagedDataAccess
因此它可以与EF6一起工作(显然 - 一年前的大多数文章 - Oracle.DataAccess
不适用于EF6只有EF5)。
我的 Web.Config 如下:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
</sectionGroup>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<connectionStrings>
<add name="Default" providerName="Oracle.ManagedDataAccess.Client" connectionString="DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host_123)(PORT=1234)))(CONNECT_DATA=(SID=hostprd)(SERVER=DEDICATED)));MIN POOL SIZE=3;PASSWORD=123_syst;PERSIST SECURITY INFO=True;USER ID=Userid; Connection Lifetime=16; Connection Timeout=8" />
<!--<add name="InventoryTrackerContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\InventoryTrackerDBDev-4.mdf;Initial Catalog=InventoryTrackerDBDev-4;Integrated Security=True" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<appSettings>
<add key="DefaultConnection" value="Default" />
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="MvcSiteMapProvider_IncludeAssembliesForScan" value="InventoryTracker" />
<add key="MvcSiteMapProvider_UseExternalDIContainer" value="false" />
<add key="MvcSiteMapProvider_ScanAssembliesForSiteMapNodes" value="true" />
</appSettings>
<system.web>
<!-- Active Directory Authentication - http://www.asp.net/mvc/overview/older-versions-1/security/authenticating-users-with-windows-authentication-cs -->
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.WebRequestTrackingModule, Microsoft.ApplicationInsights.Extensibility.Web" />
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" /><add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /><add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" /></httpModules>
<pages>
<namespaces>
<add namespace="GridMvc" />
<add namespace="MvcSiteMapProvider.Web.Html" />
<add namespace="MvcSiteMapProvider.Web.Html.Models" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<!--
http errors allows us to override default errors.
errorMode="Custom" means that IIS will always serve our custom pages.
if you want to see details while in develoment mode, set to DetailedLocalOnly.
for this demo, we have it set to Custom.
-->
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/Error" />
</httpErrors>
<modules>
<remove name="FormsAuthentication" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.WebRequestTrackingModule, Microsoft.ApplicationInsights.Extensibility.Web" preCondition="managedHandler" />
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" /><add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" /><add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" /></modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<publisherPolicy apply="no" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<contexts>
<context type="InventoryTracker.DAL.InventoryTrackerContext, InventoryTracker">
<databaseInitializer type="InventoryTracker.DAL.InventoryInitializer, InventoryTracker" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</entityFramework>
<elmah>
<!--
See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
more information on remote access and securing ELMAH.
-->
<security allowRemoteAccess="false" />
</elmah><location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<!--
See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
more information on using ASP.NET authorization securing ELMAH.
<authorization>
<allow roles="admin" />
<deny users="*" />
</authorization>
-->
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
</configuration>
然后在我的MVC5项目中,我有一个名为DAL
的文件夹,其中我有2个文件:
InventoryTrackerContext.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using InventoryTracker.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using InventoryTracker.DAL;
using Oracle.ManagedDataAccess.Client;
using System.Configuration;
namespace InventoryTracker.DAL
{
public class InventoryTrackerContext : DbContext
{
public InventoryTrackerContext()
//: base("InventoryTrackerContext")
: base( new OracleConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString), true)
{
}
public DbSet<INV_Assets> INV_Assets { get; set; }
public DbSet<INV_Models> INV_Models { get;set; }
public DbSet<INV_Manufacturers> INV_Manufacturers { get;set; }
public DbSet<INV_Types> INV_Types { get; set; }
public DbSet<INV_Locations> INV_Locations { get; set; }
public DbSet<INV_Vendors> INV_Vendors { get; set; }
public DbSet<INV_Statuses> INV_Statuses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<INV_Assets>().MapToStoredProcedures();
}
public System.Data.Entity.DbSet<InventoryTracker.Models.INV_Owners> INV_Owners { get; set; }
public System.Data.Entity.DbSet<InventoryTracker.Models.INV_AssetsHistory> INV_AssetsHistory { get; set; }
}
}
InventoryInitializer :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using InventoryTracker.Models;
using InventoryTracker.DAL;
using WebMatrix.WebData;
namespace InventoryTracker.DAL
{
public class InventoryInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<InventoryTrackerContext>
{
InventoryTrackerContext context = new InventoryTrackerContext();
protected override void Seed(InventoryTrackerContext context)
{
List<INV_Locations> invLocs = getLocations();
invLocs.ForEach(s => context.INV_Locations.Add(s));
List<INV_Manufacturers> invManufacturers = getManufacturers();
invManufacturers.ForEach(s => context.INV_Manufacturers.Add(s));
List<INV_Models> invModels = getModels();
invModels.ForEach(s => context.INV_Models.Add(s));
List<INV_Statuses> invStatuses = getStatuses();
invStatuses.ForEach(s => context.INV_Statuses.Add(s));
List<INV_Types> invTypes = getTypes();
invTypes.ForEach(s => context.INV_Types.Add(s));
List<INV_Vendors> invVendors = getVendors();
invVendors.ForEach(s => context.INV_Vendors.Add(s));
List<INV_Assets> invAssets = getAssets();
invAssets.ForEach(s => context.INV_Assets.Add(s));
context.SaveChanges();
}
// SEED CODE THAT DOESN'T APPEAR TO RUN? THIS FILE IS REFERENCED IN WEB.CONFIG
}
}
然后在我的Migrations
文件夹中,我有一个名为 Configuration.cs 的文件:
namespace InventoryTracker.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using System.Globalization;
using InventoryTracker.Models;
using InventoryTracker.DAL;
using WebMatrix.WebData;
internal sealed class Configuration : DbMigrationsConfiguration<InventoryTracker.DAL.InventoryTrackerContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(InventoryTracker.DAL.InventoryTrackerContext context)
{
List<INV_Locations> invLocs = getLocations();
context.INV_Locations.AddRange(invLocs);
context.SaveChanges();
List<INV_Manufacturers> invManufacturers = getManufacturers();
context.INV_Manufacturers.AddRange(invManufacturers);
context.SaveChanges();
List<INV_Models> invModels = getModels();
context.INV_Models.AddRange(invModels);
context.SaveChanges();
List<INV_Statuses> invStatuses = getStatuses();
context.INV_Statuses.AddRange(invStatuses);
context.SaveChanges();
List<INV_Types> invTypes = getTypes();
context.INV_Types.AddRange(invTypes);
context.SaveChanges();
List<INV_Vendors> invVendors = getVendors();
context.INV_Vendors.AddRange(invVendors);
context.SaveChanges();
List<INV_Assets> invAssets = getAssets();
context.INV_Assets.AddRange(invAssets);
List<INV_AssetsHistory> invAssetsHistory = getAssetHistories();
context.INV_AssetsHistory.AddRange(invAssetsHistory);
context.SaveChanges();
}
// Various GET() Code, this is where the Seeding DOES Occur as opposed to file above.
}
当我在 Web.config 中为InventoryTrackerContext
定义了连接字符串时,我可以创建新的迁移(add-migration InitialCreate
),然后运行(update-database
使用我在 Configuration.cs 中指定的数据来种植我的LocalDB文件。
现在我正在尝试使用ORACLE
连接["Default"]
并通过类似的上下文访问,我遇到了问题。我创建了一个新的迁移,但是当我尝试运行(update-database
)时,我会收到以下内容:
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201503251604557_InitialCreate].
Applying explicit migration: 201503251604557_InitialCreate.
System.NotImplementedException: The method or operation is not implemented.
at Oracle.ManagedDataAccess.EntityFramework.OracleMigrationSqlGenerator.Generate(CreateProcedureOperation createProcedureOperation)
at CallSite.Target(Closure , CallSite , OracleMigrationSqlGenerator , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at CallSite.Target(Closure , CallSite , OracleMigrationSqlGenerator , Object )
at Oracle.ManagedDataAccess.EntityFramework.OracleMigrationSqlGenerator.<GenerateStatements>b__2(Object op)
at Oracle.ManagedDataAccess.EntityFramework.EntityUtils.Each[T](IEnumerable`1 ts, Action`1 action)
at Oracle.ManagedDataAccess.EntityFramework.OracleMigrationSqlGenerator.GenerateStatements(IEnumerable`1 migrationOperations)
at Oracle.ManagedDataAccess.EntityFramework.OracleMigrationSqlGenerator.Generate(IEnumerable`1 migrationOperations, String providerManifestToken)
at System.Data.Entity.Migrations.DbMigrator.GenerateStatements(IList`1 operations, String migrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.GenerateStatements(IList`1 operations, String migrationId)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
The method or operation is not implemented.
然后,如果我尝试运行该应用程序,请使用var assetList = _db.INV_Assets.ToList()
在以下代码标记中An exception of type 'System.NotImplementedException' occurred in EntityFramework.dll but was not handled in user code. Additional information: The method or operation is not implemented.
:
namespace InventoryTracker.Controllers
{
public class HomeController : Controller
{
InventoryTrackerContext _db = new InventoryTrackerContext();
public ActionResult Index(INV_Assets defModel)
{
var assetList = _db.INV_Assets.ToList();
return View(assetList);
//return View(defModel);
}
有人能找到我错的地方吗?我试图通过db
变量和实体框架访问我的ORACLE context
,就像我使用本地数据库文件一样。