使用EF操作Oracle数据库小计

1、建表

CREATE TABLE item.ORDERS(
   ORDERID NUMBER(20) CONSTRAINT PK_ORDERS PRIMARY KEY,
   ORDERNO VARCHAR2(20),
   STOREID NUMBER(20),
   STOREOWNERID NUMBER(20),
   CUSTOMERID NUMBER(20),
   ORDERTYPE NUMBER(3),
   ORDERSTATUS NUMBER(3)
   );

2、ID自增列设置

create sequence ITEM_ORDERS_SEQ
minvalue 1    -- 最小值=1
maxvalue 999999999999999999999999999  -- 指定最大值
-- 或nomaxvalue      -- 没有最大值
-- NOCYCLE;      -- 不循环
start with 1   -- 从1开始
increment by 1  -- 每次递增1
cache 20;  

create or replace trigger ITEM_ORDERS_TRI
  before insert ON item.orders   --表名
  for each row
declare
  nextid number;
begin
  IF :new.ORDERID IS NULL or :new.ORDERID=0 THEN --ORDERID为列名
    select ITEM_ORDERS_SEQ.nextval
    into nextid
    from sys.dual;
    :new.ORDERID:=nextid;
  end if;
end ITEM_ORDERS_TRI;

3、nuget引用包(先删除已有的包,再按1、2、3次序依次引入)

4、连接串配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <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.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory,Oracle.ManagedDataAccess.EntityFramework,Version=6.122.1.0,Culture=neutral,PublicKeyToken=89b483f429c47342" />
    <providers>
      <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </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.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
  </system.data>
  <connectionStrings>
    <add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=item;Password=yungou;Data Source=order_db" />
  </connectionStrings>
  <oracle.manageddataaccess.client>
    <version number="*">
      <dataSources>
        <dataSource alias="order_db" descriptor="(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.96)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)))" />
      </dataSources>
      <edmMappings>
        <edmMapping dataType="number">
          <add name="bool" precision="1" />
          <add name="byte" precision="3" />
          <add name="int16" precision="5" />
          <add name="int32" precision="10" />
          <add name="int64" precision="19" />
        </edmMapping>
      </edmMappings>
    </version>
  </oracle.manageddataaccess.client>
  <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.122.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

5、映射管理

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace EF.Oracle
{
    /// <summary>
    /// OracleDbContext
    /// </summary>
    public class OracleDbContext : DbContext
    {
        /// <summary>
        /// OracleDbContext
        /// </summary>
        public OracleDbContext()
            : base("OracleDbContext")
        {

        }

        public DbSet<Order> Orders { get; set; }

        /// <summary>
        /// OnModelCreating
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("ITEM");
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<DatabaseGeneratedAttributeConvention>();

            modelBuilder.Entity<Order>().ToTable("ORDERS");
            //自增列需要在数据库建序列+触发器配合生成
            modelBuilder.Entity<Order>().HasKey(o => o.OrderId);
            modelBuilder.Entity<Order>().Property(o => o.OrderId).HasColumnName("ORDERID");
            modelBuilder.Entity<Order>().Property(o => o.OrderNo).HasColumnName("ORDERNO");
            modelBuilder.Entity<Order>().Property(o => o.StoreId).HasColumnName("STOREID");
            modelBuilder.Entity<Order>().Property(o => o.StoreOwnerId).HasColumnName("STOREOWNERID");
            modelBuilder.Entity<Order>().Property(o => o.CustomerId).HasColumnName("CUSTOMERID");
            modelBuilder.Entity<Order>().Property(o => o.OrderType).HasColumnName("ORDERTYPE");
            modelBuilder.Entity<Order>().Property(o => o.OrderStatus).HasColumnName("ORDERSTATUS");
        }
    }
}

/*
 * 自增列实现SQL
 *
create sequence ITEM_ORDERS_SEQ
minvalue 1    -- 最小值=1
maxvalue 999999999999999999999999999  -- 指定最大值
-- 或nomaxvalue      -- 没有最大值
-- NOCYCLE;      -- 不循环
start with 1   -- 从1开始
increment by 1  -- 每次递增1
cache 20;  

create or replace trigger ITEM_ORDERS_TRI
  before insert ON item.orders   --表名
  for each row
declare
  nextid number;
begin
  IF :new.ORDERID IS NULL or :new.ORDERID=0 THEN --ORDERID为列名
    select ITEM_ORDERS_SEQ.nextval
    into nextid
    from sys.dual;
    :new.ORDERID:=nextid;
  end if;
end ITEM_ORDERS_TRI;
*/

6、实体模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF.Oracle
{
    public class Order
    {
        public long OrderId { get; set; }
        public string OrderNo { get; set; }

        public long StoreId { get; set; }

        /// <summary>
        /// 店主Id
        /// </summary>
        public long StoreOwnerId { get; set; }

        /// <summary>
        /// 买家Id
        /// </summary>
        public long CustomerId { get; set; }

        /// <summary>
        /// 订单类型
        /// </summary>
        public int OrderType { get; set; }

        /// <summary>
        /// 订单状态
        /// </summary>
        public int OrderStatus { get; set; }
    }
}

7、调用

using System;
using System.Data.Entity;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
using System.Text;

namespace EF.Oracle
{
    class Program
    {
        static OracleDbContext dbContext = new OracleDbContext();
        static void Main(string[] args)
        {
            dbContext.Database.Log = Console.WriteLine; //ef生成sql日志跟踪 https://www.cnblogs.com/huangxincheng/p/5911448.html
            var q = (from p in dbContext.Orders where p.OrderId > 1000
                select p).Any();
            Console.WriteLine(q.ToString());

            CreateOrder();
            QueryOrder();
            EditOrder();
            QueryOrder();
            Console.WriteLine("ok");

            Console.Write("Press any key to continue... ");
            Console.ReadLine();
        }

        private static void CreateOrder()
        {
            DeleteOrder();

            Order o = new Order
            {
                OrderNo = "777888999",
                CustomerId = 2222,
                OrderStatus = 10,
                OrderType = 10,
                StoreId = 24455,
                StoreOwnerId = 8888
            };

            dbContext.Orders.Add(o);
            dbContext.SaveChanges();
        }

        private static void EditOrder()
        {
            var order = dbContext.Orders.FirstOrDefault(o => o.OrderNo.Equals("777888999"));
            if (order != null)
            {
                order.CustomerId = 9999;
                order.OrderType = 20;

                dbContext.SaveChanges();
            }
        }

        private static void DeleteOrder()
        {
            var order = dbContext.Orders.FirstOrDefault(o => o.OrderNo.Equals("777888999"));
            if (order != null)
            {
                dbContext.Orders.Remove(order);
                dbContext.SaveChanges();
            }
        }

        private static void QueryOrder()
        {
            var order = dbContext.Orders.FirstOrDefault(o => o.OrderNo.Equals("777888999"));
            if (order != null)
            {
                Console.WriteLine(string.Format("{0}-{1}-{2}", order.OrderId, order.OrderNo, order.CustomerId));
            }
        }
    }
}

8、输出

原文地址:https://www.cnblogs.com/huangzelin/p/8252995.html

时间: 2024-11-05 02:20:01

使用EF操作Oracle数据库小计的相关文章

Java操作Oracle数据库以及调用存储过程

操作Oracle数据库 publicclass DBConnection {     //jdbc:oracle:thin:@localhost:1521:orcl     publicstaticfinal String url = "jdbc:oracle:thin:@localhost:1521:ORCL";     publicstatic Connection conn ;         static{         //获取数据库驱动         try {    

JFinal框架操作oracle数据库

JFinal框架操作oracle数据库,需要在configPlugin()方法中配置链接oracle数据库的相关配置 配置JFinal数据库操作插件,configPlugin方法 这里我加载jdbc.properties配置文件实在configConstant加载的 @Override public void configConstant(Constants me) { loadPropertyFile("jdbc.properties");//加载配置文件 me.setDevMode

使用ADO.NET操作Oracle数据库

本文将示例使用C#的ADO.NET技术调用Oralce的存储过程和函数及操作Oracle数据库. 在oracle的hr数据库中建立存储过程 在oralce的hr数据库中建立函数 新建控制台项目,在主函数添加代码: 1 string strConn = "Data Source=jayjay;User ID=hr;Password=oracle;Unicode=True"; 2 3 //调用存储过程 4 using (OracleConnection conn = new OracleC

java PreparedStatement操作oracle数据库

import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; //import java.sql.Statement; import java.sql.PreparedStatement; public class lx02{ public static void main(String[] args) throws SQLException, ClassNotFoundException

Java操作Oracle数据库自建工具库

在学习Java操作Oracle数据库的时候,忽然想到这个可不可以像php那样自己建立一个工具类,这样的话可以大大的减小代码的复杂度.也可以提高工作效率. java如果不能自己建立工具类,那是非常可笑的,但是,在建立的过程中,出现了一些问题,希望在以后不要犯类似的错误. 首先,我们在自建工具类之前必然是先模拟测试的,在这个例子当中,其过程如下: 1:引入Oracle的驱动程序 2:建立OracleTools类,并且定义其成员变量. 3:写OracleTools类的成员方法和构造函数. 4:如果全部

Python使用cx_Oracle模块连接操作Oracle数据库

1. 简介 cx_Oracle 是一个用来连接并操作 Oracle 数据库的 Python 扩展模块, 支持包括 Oracle 9.2 10.2 以及 11.1 等版本 2.安装 最后是去官网http://cx-oracle.sourceforge.net/上下载安装,我自己通过pip和easy install安装都失败了,我是在win8.1的环境下安装的 3.使用 使用就很简单,以下为代码示例 #!/usr/bin/env python #-*- coding:utf-8 -*- import

ASP.NET操作ORACLE数据库之模糊查询

ASP.NET操作ORACLE数据库之模糊查询 一.ASP.NET MVC利用OracleHelper辅助类操作ORACLE数据库 1 //连接Oracle数据库的连接字符串 2 string connectionString = @"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) 3 (HOST=localhost) (PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=TestDB)))

连接Linux服务器操作Oracle数据库

连接Linux服务器操作Oracle数据库 由于项目已经上线,现场的数据库服务器不允许直接用Oracle的客户端plsqldev.exe来连接,只能通过Linux服务器的命令来操作. 以下是用SecureCRT 5.1客户端连接Linux服务器来操作Oracle数据库: 1.连接到Linux服务器(输入服务器的ip地址) ssh 10.199.94.227 连接成功后会提示输入密码,输入成功会提示. 2.切换到操作Oracle数据库 su - oracle 切换成功会提示相关数据库的实例.例如:

PHP操作Oracle数据库

原文出处 (这是来自“百度文库”中的文章写得很不错) PHP操作Oracle数据库(OCI数据抽象层)OCI(Oracle 8 Call-Interface)是PHP中内置的数据库抽象层函数.下面针对连接Oracle数据库操作数据库的常见任务举例说明:=======================基本查询:无条件查询===================1.数据库连接:函数:oci_connect()函数:resource oci_connect ( string username, strin