用 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();
            }
        }
    }

  

調用后,發現可以獲取數據。 沒有經過復雜的測試。 可能其他地方會有問題。且行且測試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM