The chicken dish NetCore use EF to operate the database Oracle & Sqlserver (a)

Summary:

  This article is mainly to document how netCore EFCore operate Oracle and SqlServer databases, create databases and tables using Codefirst way.

First, the project established

  DDD project using domain-driven design patterns [learning], catalog description

  1. Application: the service layer, temporarily established [service]

  2. Domain: business layer, mainly some of the warehousing business logic has been defined, the current definition database entities and warehousing defined

  3. Infrastructure: Infrastructure layer, the provision of public functional components, to achieve the current project realization Oracle & Sqlserver database operations and warehousing

  4.Presentation: WebApi placed it feels inappropriate, but also seems inappropriate on Application

II. Database entities (tables) Design

  1. Create a new folder in the project Demo.Core Entities, the main storage folder database entity related information, here contains only one entity STUDENT

  2. New Student.cs class in Entites folder

. 1  namespace Demo.Core.Entities
 2  {
 . 3      [the Table ( " the STUDENT " )]   // specify the database name correspondence table 
. 4      public  class Student
 . 5      {
 . 6          ///  <Summary> 
. 7          /// student number
 8          ///  < / Summary> 
. 9          [key]   // primary key 
10          [the column ( " the USERID " )] // the specified database table corresponding to the field name 
. 11          public  String the UserId { GET ; SET; }
12 
13         /// <summary>
14         /// 学生姓名
15         /// </summary>
16         [MaxLength(10)]
17         [Column("NAME")]
18         public string Name { get; set; }
19     }
20 }
View Code

  Filled pit Record: Specify the database table names and field size when called, otherwise we use PL / SQL query will join the quotes because PL / SQL is not case sensitive and some tools, very easy to use. If forced to use hump named in a database query tool as follows:

1 SELECT "UserId","Name" FROM "Student";

III. Creating DbContext

  1. Project Demo.EFCore in Nuget database-driven package

    Oracle => Oracle.EntityFrameworkCore [so far is a pre-release version 2.19.0-beta4]  

    SqlServer => Microsoft.EntityFrameworkCore stable version 2.2.4 [so far]

    You can be installed at the same time if necessary. In search Oracle driver when to select the next pre-release version contains []

  2. Add references to the project Demo.Core

  3. New DemoDBContext.cs

. 1  namespace Demo.EFCore
 2  {
 . 3      public  class DemoDbContext: the DbContext
 . 4      {
 . 5          public DemoDbContext (DbContextOptions <DemoDbContext> Options)
 . 6              : Base (Options)
 . 7          {
 . 8  
. 9          }
 10  
. 11          // where you define the mapping into the database table
 12          // fixed format 
13 is          public DbSet <Student> Student { GET ; SET ;}
 14  
15          protected  the override  voidOnModelCreating (the ModelBuilder modelBuilder)
 16          {
 . 17              // determines whether the current need to manually add the Oracle database Schema (account name database DBA supplied) 
18 is              IF ( the this .Database.IsOracle ())
 . 19              {
 20 is                  modelBuilder.HasDefaultSchema ( " NETCORE " );
 21 is              }
 22 is              Base .OnModelCreating (modelBuilder);
 23 is          }
 24  
25      }
 26 is }
View Code

     Filled pit recording: If you are using Oracle Schema must be added manually

 IV. Configuring Demo.WebApi project

  1. Add a project reference to Demo.EFCore

  2. Modify profile appsetting.json, add the connection string information DbConn, the following code

 1 {
 2   "Logging": {
 3     "LogLevel": {
 4       "Default": "Warning"
 5     }
 6   },
 7   "AllowedHosts": "*",
 8   "DbConn": {
 9     "OraConn": "User Id=netcore;Password=netcore2019;Data Source=10.244.247.124:1521/ORCL;",
10     "SqlConn": "Server=10.244.4.236\\NEMO;Database=NETCORE;User ID=sa;Password=Sa2016;"
11   }
12 }
appsetting.json

  3. Modify Startup.cs file, modify the method of registration ConfigureServices Oralce & SqlServer connection

ConfigureServices

  Needed to use Oracle or SqlServer, the current mode can only choose one.

  Fill hole record: When using the Oracle DBA will be sure to please a good account establishment

V. database migration

  1. Set Demo.WebApi as a system startup items

  2. Open the package management console => default project selection Demo.EFCore

  3. Enter the console: Add-Migration Init

    At this time will generate a file in the folder in Demo.EFCore Migrations, the recorded data file migration recorded

  4. console input: Update-DataBase

  The database has been generated look-up table

  If the modified entity object (such as a table or modify new table field), to sequentially perform steps 3 and 4 corresponding to the modified database to save the results.

  Extended:

  1. dbContext.Database.EnsureDeleted (); dbContext.Database.EnsureCreated (); with these two methods can be simple and crude will be deleted from the database in the reconstruction, would not have to manually enter the command for migration, it is clear that doing so will result in the database existing data loss.

  2. We can also use dbContext.Database.Migrate () instead of entering the "Update-DataBase" command automatically migrated in the program, but instead "Add-Migration" command not found.

VI. Initialize the database table values

  We generally on the line item, the database will be some initial value, in CodeFirst mode, we will generate a value of the injected through code in the database.

  1. Demo.EFCore New DemoInitial.cs

. 1  public  class DemoInitial
 2      {
 . 3          public  static  void the Initial (the DbContext DbContext)
 . 4          {
 . 5              // brute create the database
 6              // delete the newly created database database
 7              // If error deleted, can be deleted to the database manually
 . 8              // DbContext. Database.EnsureDeleted ();
 . 9              // dbContext.Database.EnsureCreated ();
 10  
. 11              // program automatically detects whether or not the new migration does not respond to the data, the database is updated with a 
12 is              IF . (dbContext.Database.GetPendingMigrations () ToList () .Count ()> 0 )
 13 is              {
14                  dbContext.Database.Migrate ();
 15              }
 16              
. 17              // based on one table if there is data to be injected is determined whether the initial data 
18 is              IF (dbContext.Set <Student>! () .ANY ())
 . 19              {
 20 is                  var = Student new new Student ()
 21 is                  {
 22 is                      the UserId = " C3700408 " ,
 23 is                      the Name = " Nemo " 
24                  };
 25                  dbContext.Set <Student> () .Add (Student);
 26 is                 dbContext.SaveChanges();
27             }
28 
29 
30         }
31     }
View Code

  2. Modify Demo.WebApi Program, because we have to do these things when the project starts

 1  public static void Main(string[] args)
 2         {
 3             var host = CreateWebHostBuilder(args).Build();
 4             using (var scope = host.Services.CreateScope())
 5             {
 6                 var services = scope.ServiceProvider;
 7                 try
 8                 {
 9                     DemoDbInitial.Initial(services.GetService<DemoDbContext>());
10                 }
11                 catch (Exception ex)
12                 {
13                     //Do something
14                 }
15             }
16             host.Run();
17         }
View Code

  3. Run the code, the database is detected

to sum up:

Click for source

Guess you like

Origin www.cnblogs.com/NemoWork/p/11013597.html