oracle EF core hello world

  1. 在oracle数据库里建一个表
    CREATE TABLE student (
        num int not null,
        name varchar2(200) not null,
        PRIMARY KEY(num)
     );
    
  2. 通过vs studio2022建一个"控制台应用"类型的项目.
  3. 通过vs studio上的nuget下载Oracle.EntityFrameworkCore,Microsoft.EntityFrameworkCore.Tools
  4. 使用EF core的代码如下:
    using Microsoft.EntityFrameworkCore;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    namespace d0001_efc1
    {
        class Program
        {
            public class StudentContext : DbContext
            {
                public DbSet<Student>? Students { get; set; }
    
    
                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                {
                    optionsBuilder.UseOracle(@"User Id=test_user;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=aaa)))");
                }
            }
            [Table("STUDENT")]
            public class Student
            {
                [Column("NUM")]
                [Key]
                public int num { get; set; }
                [Column("NAME")]
                public string? name { get; set; }
    
    
            static void Main(string[] args)
            {
                using (var db = new StudentContext())
                {
                    var student = new Student { num = 4, name = "张三" };
                    db.Students!.Add(student);
                    db.SaveChanges();
                }
    
                using (var db = new StudentContext())
                {
                    var blogs = db.Students;
                    foreach (var item in blogs!)
                    {
                        Console.WriteLine(item.name);
                            Console.WriteLine(item.num);
                            //Console.WriteLine(item.Url + " has rating " + item.Rating );
                        }
                }
                Console.ReadLine();
            }
        }
        }
    }
    
  5. 参考资料
    oracle EF core官方demo

posted on 2024-07-27 11:08  荷楠仁  阅读(7)  评论(0编辑  收藏  举报

导航