使用EF 6和Oracle.ManagedDataAccess

时间:2016-02-15 07:24:15

标签: c# asp.net-mvc oracle entity-framework oracle-manageddataaccess

我正在使用EF 6.0.0.0和ODP.Net Oracle.ManagedDataAccess版本4.121.2.0创建MVC应用程序以进行数据访问。

在名为Controller的{​​{1}}中,我有以下代码段:

EmployeeController

当我加载public ActionResult Details(int id) { try { EmployeeContext employeeContext = new EmployeeContext(); Employee employee = employeeContext.Employees.Single(x => x.Id == id); //Here the exception occurs! return View(employee); } catch (Exception e) { return View(e); } } 页面时,我得到以下例外:

  

"执行命令定义时发生错误。见   详细内部异常。"

在内部异常中,它说:

  

ORA-00942:表或视图不存在

这让我很困惑,因为在我的Oracle数据库中,该表肯定存在(我使用Toad for Oracle检查过):

enter image description here

数据库本身的Employee/Details.cshtml与我用于其他项目的连接字符串相同,我可以毫不费力地从数据库中查询数据。

以下是我在connectionString中声明Employee类的方法:

Models/Employee.cs

我的using System.ComponentModel.DataAnnotations.Schema; . . . [Table("TBLEMPLOYEE")] //the same table name public class Employee { public int Id { get; set; } public string Name { get; set; } public string Gender { get; set; } public DateTime DateOfBirth { get; set; } public int EmployeeType { get; set; } public double? AnnualSalary { get; set; } public double? HourlyPay { get; set; } public double? HoursWorked { get; set; } public string City { get; set; } } 只包含一个元素:

Models/EmployeeContext.cs

using System.Data.Entity; . . . public class EmployeeContext : DbContext { public DbSet<Employee> Employees { get; set; } } 文件中,我已初始化Global.asax.cs模型的数据库:

EmployeeContext

如果表不存在,我还会得到什么错误?这可能会出错?有什么建议如何调试这种情况?

修改:

当我评估protected void Application_Start() { //executed at the very beginning Database.SetInitializer<MvcWebApplication1.Models.EmployeeContext>(null); //null -> no initialization strategy AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } 时,我得到以下值:

employeeContext.Employees

编辑2:

使用:

{SELECT 
"Extent1"."Id" AS "Id", 
"Extent1"."Name" AS "Name", 
"Extent1"."Gender" AS "Gender", 
"Extent1"."DateOfBirth" AS "DateOfBirth", 
"Extent1"."EmployeeType" AS "EmployeeType", 
"Extent1"."AnnualSalary" AS "AnnualSalary", 
"Extent1"."HourlyPay" AS "HourlyPay", 
"Extent1"."HoursWorked" AS "HoursWorked", 
"Extent1"."City" AS "City"
FROM "dbo"."TBLEMPLOYEE" "Extent1"}

我的调试输出窗口中有以下内容:

employeeContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

编辑3:

这是我的连接字符串的样子,以防万一需要

SELECT 
"Extent1"."Id" AS "Id", 
"Extent1"."Name" AS "Name", 
"Extent1"."Gender" AS "Gender", 
"Extent1"."DateOfBirth" AS "DateOfBirth", 
"Extent1"."EmployeeType" AS "EmployeeType", 
"Extent1"."AnnualSalary" AS "AnnualSalary", 
"Extent1"."HourlyPay" AS "HourlyPay", 
"Extent1"."HoursWorked" AS "HoursWorked", 
"Extent1"."City" AS "City"
FROM "dbo"."TBLEMPLOYEE" "Extent1"
WHERE ("Extent1"."Id" = :p__linq__0) AND (ROWNUM <= (2) )

entityFramework的设置如下:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcWebApplication1-20160212010850.mdf;Initial Catalog=aspnet-MvcWebApplication1-20160212010850;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="EmployeeContext" connectionString="Data source=thisisfakedatasource;user id=thisisfakename;password=thisisfakepassword;persist security info=True"
      providerName="Oracle.ManagedDataAccess.Client"/>
  </connectionStrings>  

问题可能是什么线索?

其他信息:

异常堆栈跟踪:

  <entityFramework>
    <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>

内部异常堆栈跟踪:

e.StackTrace

   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
   at MvcWebApplication1.Controllers.EmployeeController.Details(Int32 id) in c:\myapp\Controllers\EmployeeController.cs:line 25

2 个答案:

答案 0 :(得分:5)

评论中DevilSuichiro建议找不到Data Table的原因是由于使用了错误的Schema。默认情况下,EF 6使用dbo作为默认架构,而我的架构不是dbo。要使模型具有默认架构,需要覆盖OnModelCreating事件:

public class EmployeeContext : DbContext {
    public DbSet<Employee> Employees { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.HasDefaultSchema("myschema");
    }
}

另外,感谢Ivan Stoev建议检查EF生成的SQL。

答案 1 :(得分:1)

我们遇到了同样的问题。 我们发现对edmx文件中错误的数据库架构的引用:

<EntitySet Name="MyTable" EntityType="Self.MyTable" Schema="**wrongSchemaName**" store:Type="Tables" />

通过删除架构名称,我们的问题已解决。

<EntitySet Name="MyTable" EntityType="Self.MyTable" Schema="" store:Type="Tables" />