用 Entity Framework结合Oracle数据库来开发项目

项目需要,要使用Oracle 11g数据库。作为不想写SQL的程序员,所以......

原先想当然的是使用EF+MSSQL的方式来进行配置。吃了哑巴亏。然后谷歌出了一篇好文,沿着这篇文章进行了搭建,It's Working.

然后我现在就把这篇文章搬过来, 原文地址:http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/NuGet/index.html#overview


时间有限,还是讲重点就好。 

打开NuGet:

 

按照上面的步骤,在Nuget里面联机搜索 Oracle。 找到图中的那个库。进行安装,包含了Ef。

然后就去配置web.config的数据库连接串。我的:

 <add name="oracleConn" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=dm;Password=s;Data Source=10.7.9.8/od" />

  

简单易懂。

然后呢。 Ef该怎么配置就怎么配置。

要注意的是,Oracle里面如果全是大写的。那么你的对象也必须是大写的。 不然会报错。 当然可以通过映射来改变,如下。

实体:

public class Role
    {
        public int ID { get; set; }

        public int? P_ID { get; set; }

        public string RoleName { get; set; }

        public string Remark { get; set; }

        public string CreMan { get; set; }

        public DateTime? Create_Date { get; set; }

        public string UpdMan { get; set; }

        public DateTime? Update_Date { get; set; }

        public string Is_Del { get; set; }

        public int Version_No { get; set; }

    }

  

映射:

public class Role_Mapping : EntityTypeConfiguration<Role>
    {
        public Role_Mapping()
        {
            this.ToTable("MD_ROLE");
            this.Property(t => t.RoleName).HasColumnName("ROLE");
            this.Property(t => t.Create_Date).HasColumnName("CREATE_DATE");
            this.Property(t => t.CreMan).HasColumnName("CREMAN");
            this.Property(t => t.Is_Del).HasColumnName("IS_DEL");
            this.Property(t => t.Remark).HasColumnName("REMARK");
            this.Property(t => t.Update_Date).HasColumnName("UPDATE_DATE");
            this.Property(t => t.UpdMan).HasColumnName("UPDMAN");
            this.Property(t => t.Version_No).HasColumnName("VERSION_NO");
        }
    }

  

然后呢,ef会给默认的表名家 dbo,这是SQLSERVER的东西吧,Oracle也有吧。 这东西好像叫 Schema。

我们要在Ef上下文类的OnModelCreating方法里面进行修改,如下:

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

  

是的,设置为空字符串就好了。额,为什么没用string.Empty. 我去改下。

我的测试代码如下:

public class RoleService : IRoleService
    {
        public void GetRoles()
        {
            using (var ctx = new KjContext())
            {
               var roles = ctx.Role.Where(s => true).ToList();
               var roles2 = ctx.Role.Where(s => s.P_ID != null).Select(s => s.RoleName).ToList();
               var roles3 = ctx.Role.Where(s => s.Create_Date != null && s.Create_Date < DateTime.Now).Select(s => s.RoleName).ToList();
            }
        }
    }

  

调用后,发现可以获取数据。 没有经过复杂的测试。 可能其他地方会有问题。且行且测试。

原文地址:https://www.cnblogs.com/saving/p/5653679.html