Entity Framework 示例 6 + Code First + Oracle 12c

Sample for Entity Framework 6 + Code First + Oracle 12c

我对使用 Entity Framework 6 + Code First + Oracle 12c 的 Visual Studio 解决方案有疑问。我不确定它是否配置正确,或者我是否遗漏了一些简单的东西。

我试图寻找一个示例项目作为开始,但找不到 - google 搜索、Whosebug 等

有没有什么地方有一个简约的示例项目,它会在运行时尝试创建数据库?

更新:为了确保,我没有要求任何人为我创建示例。在我开始之前,我想确保确实没有现成的样本(这对我来说很奇怪,但很可能是这种情况)。

我设法创建了一个工作示例。发现了一些(并非如此)记录在案的奇怪行为,导致 运行 时间错误。

这是完整的样本来源:https://drive.google.com/file/d/0By3P-kPOnpiGRnc0OG5ZTDl6eGs/view?usp=sharing&resourcekey=0-ecT1EU81wJOQWokVDr_r9w

我用 Visual Studio 2013 创建了示例。使用 nuget 来拉取

  • EntityFramework6.1.3
  • 官方 Oracle ODP.NET,托管 Entity Framework 驱动程序 12.1.021

重要的部分是

  • Program.cs
  • Context.cs
  • TestEntity.cs
  • App.config

我省略了

  • packages.config
  • AssemblyInfo.cs
  • csproj, sln 文件 我也省略了命名空间。
using System.Data.Entity;

public class Program
    {
        private static void Main(string[] args)
        {
            string connStr =
                "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=***server***)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=***SERVICE***)));Persist Security Info=True;User ID=***User***;Password=***password***";

            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context>());
            //Database.SetInitializer(new DropCreateDatabaseAlways<Context>());

            Context context = new Context(connStr);

            TestEntity te = new TestEntity();
            te.Id = 1;
            te.Name = "Test1";

            context.TestEntities.Add(te);

            context.SaveChanges();
        }
    }

using System.Data.Entity;

public class Context : DbContext
{
    public Context(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    public virtual DbSet<TestEntity> TestEntities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("OTS_TEST_EF");

        modelBuilder.Entity<TestEntity>()
            .Property(e => e.Id)
            .HasPrecision(9, 2);

        base.OnModelCreating(modelBuilder);
    }
}

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("TestEntity")]
public class TestEntity
{
    [Column(TypeName = "number")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public decimal Id { get; set; }

    [StringLength(100)]
    public string Name { get; set; }
}

<?xml version="1.0" encoding="utf-8"?>
<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"/>
    <section name="oracle.manageddataaccess.client"
      type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <entityFramework>
    <!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>-->
    <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>
  <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>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <publisherPolicy apply="no"/>
        <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
        <bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <!--<oracle.manageddataaccess.client>
    <version number="*">
      <dataSources>
        <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=INFOTEST))) "/>
      </dataSources>
    </version>
  </oracle.manageddataaccess.client>-->
  <!--<connectionStrings>
    <add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
      connectionString="Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = INFOTEST)));Persist Security Info=True;User ID=user;Password=password"/>
  </connectionStrings>-->
</configuration>

路上发现的怪事: 添加以下任何类型名称都将导致“序列不包含匹配元素”错误。

    /*[Column(TypeName = "numeric")]*/
    /*[Column(TypeName = "number(18,0)")]*/
    /*[Column(TypeName = "number(18,2)")]*/

用 0 刻度表示精度

modelBuilder.Entity<TestEntity>().Property(e => e.Id).HasPrecision(9, 0);

将导致

指定的架构无效。错误:

(7,12):错误 2019:指定的成员映射无效。类型 'EF6_Oracle12c_CF.TestEntity' 中成员 'Id' 的类型 'Edm.Decimal[Nullable=False,DefaultValue=,Precision=9,Scale=0]' 与 'OracleEFProvider.number

不兼容

省略

modelBuilder.HasDefaultSchema("OTS_TEST_EF");

行将导致

ORA-01918: 用户不存在

刚好我也得到了

ORA-00955: 名称已被现有对象使用

无法检查模型兼容性,因为数据库不包含模型元数据。只能检查使用代码优先或代码优先迁移创建的数据库的模型兼容性。

我通过启用

设法克服了这些问题
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());

行,而不是 DropCreateDatabaseIfModelChanges 模式。

这是来自 Oracle 的关于使用 EF Code First、迁移和 Visual Studio 的示例的 link。

Oracle Learning Library on EF Code First and Code First Migration

实际上我几乎要完成一个使用 VS、12c 和 EF 的项目,link 是一个很好的起点。我没有看到关于 12c 的特别问题。

如果您仍然感兴趣,这是一个很好的示例。它在 11 g 上可用。

http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/CodeFirst/index.html

我在 github 上有一个测试项目,用于在 Oracle 上试用 EF6 迁移示例。对我有用的代码(以编程方式执行所有挂起的迁移)在这里。我的用例可能很常见 - 我需要能够将我的应用程序部署到各种环境和数据中心,并让它 "the right thing" 与我的应用程序数据库的环境副本一起工作。

重要的一点是

//Arrange

Configuration config = new Configuration();
DbMigrator migrator = new DbMigrator(config);

Console.WriteLine("Migrating...");
foreach (string s in migrator.GetPendingMigrations())
{
    //Act
    Console.WriteLine("Applying migration {0}", s);
    Action act = () => migrator.Update(s);

    //Assert
    act.ShouldNotThrow();
}

我花了几天时间解决这个问题...终于解决了:
table 不存在。我检查了很多次并刷新,但问题不在 table 本身,而是顺序。 Oracle中每table创建一个序列对象来增加id。所以,如果你删除 table 确保也删除序列,否则当你再次迁移时,它会给你 ORA-00955: name is already used by an existing object.

所以,真正的问题是顺序,而不是 table。但是您不能创建新序列,因为它已经存在。 table删除的时候没有删除,需要手动删除
我希望这会对某人有所帮助。