4.DB Initialization(数据库初始化)[EF Code-First系列]

本文介绍了CodeFirst模式下数据库初始化的三种方式:使用默认名称、指定数据库名称和通过连接字符串配置。并通过实例展示了如何通过不同构造函数参数实现这些初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面的例子中,我们已经看到了Code-First自动为我们创建数据库的例子。

这里我们将要学习的是,当初始化的时候,Code-First是怎么决定数据库的名字和服务的呢???

下面的图,解释了这一切!!!

这个图解释了,数据库初始化的流程,是基于我们在上下文类中的构造函数中传递的参数。

在上面的图中,context类中的base构造器中,可以填入下面的参数:

  • 无参数(No Parameter)
  • 数据库的名字(Database Name)
  • 连接字符串的名字(Connection String Name)

无参数

如果你没有在base构造器中指定任何的参数,Code-First将会以你本地的服务器名字,也就是:{Namespace}.{Context class name}.例如下面代码中:code-First将会将会一个名字为EF1.DbContextClass的数据库。

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF1
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base()
       { }
       public DbSet<Student> Studnets { get; set; }

       public DbSet<Standard> Standards { get; set; }

       
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());

           base.OnModelCreating(modelBuilder);
       }

    }
}

数据库名字

你同样可以指定数据库的名字在base构造器中,例如:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF1
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base("MYDBHAHA")
       { }
       public DbSet<Student> Studnets { get; set; }

       public DbSet<Standard> Standards { get; set; }

       
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());

           base.OnModelCreating(modelBuilder);
       }

    }
}

 

然后生成的数据库是:

 

连接字符串

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF1
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base("ConnectionString")
       { }
       public DbSet<Student> Studnets { get; set; }

       public DbSet<Standard> Standards { get; set; }

       
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());

           base.OnModelCreating(modelBuilder);
       }

    }
}

或者这样写:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF1
{
   public class DbContextClass:DbContext
    {
       public DbContextClass()
           : base("name=ConnectionString")
       { }
       public DbSet<Student> Studnets { get; set; }

       public DbSet<Standard> Standards { get; set; }

       
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContextClass>());

           base.OnModelCreating(modelBuilder);
       }

    }
}

上面任选一种方式,改动之后,我们在配置文件中,添加下面的节点:

 <connectionStrings>
    <add name="ConnectionString" connectionString="server=.;database=EFCodeFirstDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>
  </connectionStrings>

这个节点,我一般都是加在这个位置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="ConnectionString" connectionString="server=.;database=EFCodeFirstDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
</configuration>

改好之后,我们运行程序,在数据库管理工具中就生成了我们想要的数据库:

这就是三种方式的初始化数据库了。

 

 

下面附上目录,方便查看:

在移植flashDB的时候使用fal 以及sfud的时候 设置 #define SFUD_FLASH_DEVICE_TABLE \ { \ [SFUD_W25_DEVICE_INDEX] = {.name = "norflash0",.spi.name = "QSPI1",.chip.name="W25Q64JV",.chip.mf_id =0xEF,.chip.type_id =0x40,.chip.capacity_id = 0x17,.chip.capacity =8L * 1024L * 1024L,.chip.write_mode = SFUD_WM_PAGE_256B,.chip.erase_gran = 4096,.chip.erase_gran_cmd =0x20}, \ } sfud_flash sfud_norflash0 = { .name = "norflash0", .spi.name = "QSPI1", .chip = {"W25Q64JV", SFUD_MF_ID_WINBOND, 0x40, 0x17, 8L * 1024L * 1024L, SFUD_WM_PAGE_256B, 4096, 0x20}}; /* ====================== Partition Configuration ========================== */ #ifdef FAL_PART_HAS_TABLE_CFG /* partition table */ #define FAL_PART_TABLE \ { \ {FAL_PART_MAGIC_WORD, "fdb_kvdb1", "norflash0", 0x00000000, 256 * 1024, 0}, \ {FAL_PART_MAGIC_WORD, "fdb_tsdb1", "norflash0", 256 * 1024, 256 * 1024, 0}, \ } #endif /* FAL_PART_HAS_TABLE_CFG */ /* * Copyright (c) 2020, Armink, <armink.ztl@gmail.com> * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief configuration template file. You need to rename the file to "fbd_cfg.h" and modify the configuration items in it to suit your use. */ #ifndef _FDB_CFG_H_ #define _FDB_CFG_H_ #include "stdio.h" /* using KVDB feature */ #define FDB_USING_KVDB #ifdef FDB_USING_KVDB /* Auto update KV to latest default when current KVDB version number is changed. @see fdb_kvdb.ver_num */ /* #define FDB_KV_AUTO_UPDATE */ #endif /* using TSDB (Time series database) feature */ #define FDB_USING_TSDB /* Using FAL storage mode */ #define FDB_USING_FAL_MODE /* TSDB 记录时间精度 int64_t */ #define FDB_USING_TIMESTAMP_64BIT /* the flash write granularity, unit: bit * only support 1(nor flash)/ 8(stm32f2/f4)/ 32(stm32f1) */ #define FDB_WRITE_GRAN 1 /* MCU Endian Configuration, default is Little Endian Order. */ /* #define FDB_BIG_ENDIAN */ /* log print macro. default EF_PRINT macro is printf() */ #define FDB_PRINT(...) printf(__VA_ARGS__) /* print debug information */ #define FDB_DEBUG_ENABLE #endif /* _FDB_CFG_H_ */ /* USER CODE BEGIN 1 */ /* Enable I-Cache---------------------------------------------------------*/ SCB_EnableICache(); /* Enable D-Cache---------------------------------------------------------*/ SCB_EnableDCache(); SCB->CACR |= 1 << 2; /* USER CODE END 1 */ /* MPU Configuration--------------------------------------------------------*/ MPU_Config(); /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); /* USER CODE BEGIN 2 */ MX_DMA_Init(); MX_USART1_UART_Init(); QSPI_W25Qxx_Init(); // 初始化W25Q64 printf("Clion STM32 UART Clion PANGGUOFU \r\n"); // /* SFUD initialize */ // if (sfud_init() == SFUD_SUCCESS) // { // /* enable qspi fast read mode, set four data lines width */ // sfud_qspi_fast_read_enable(sfud_get_device(SFUD_W25_DEVICE_INDEX), 4); // sfud_demo(0, sizeof(sfud_demo_test_buf), sfud_demo_test_buf); // } spi_flash_init(); //sfud_qspi_fast_read_enable(sfud_get_device(SFUD_W25_DEVICE_INDEX), 4); // 1. 验证Flash识别信息 sfud_flash *flash = sfud_get_device(SFUD_W25_DEVICE_INDEX); printf("sfud_flash name:%s index:%d flash->spi.name %s \n", (char *)flash->name, flash->index,(char *)flash->spi.name); printf("sfud_flash_chip name:%s capacity:0x%08x mf_id %x type_id %x capacity_id %x erase_gran %d \n", (char *)flash->chip.name, flash->chip.capacity,flash->chip.mf_id,flash->chip.type_id,flash->chip.capacity_id,flash->chip.erase_gran); HAL_Delay(100); #ifdef FDB_USING_KVDB { /* KVDB Sample */ struct fdb_default_kv default_kv; fdb_err_t result; default_kv.kvs = default_kv_table; default_kv.num = sizeof(default_kv_table) / sizeof(default_kv_table[0]); /* set the lock and unlock function if you want */ fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_LOCK, (void *)lock); fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_UNLOCK, (void *)unlock); /* Key-Value database initialization * * &kvdb: database object * "env": database name * "fdb_kvdb1": The flash partition name base on FAL. Please make sure it's in FAL partition table. * Please change to YOUR partition name. * &default_kv: The default KV nodes. It will auto add to KVDB when first initialize successfully. * NULL: The user data if you need, now is empty. */ result = fdb_kvdb_init(&kvdb, "env", "fdb_kvdb1", &default_kv, NULL); if (result != FDB_NO_ERR) { printf("Clion STM32 UART Clion KVDB Sample -1 \r\n"); return -1; } /* run basic KV samples */ kvdb_basic_sample(&kvdb); /* run string KV samples */ kvdb_type_string_sample(&kvdb); /* run blob KV samples */ kvdb_type_blob_sample(&kvdb); } #endif /* FDB_USING_KVDB */ 但是一直出现[SFUD]norflash0 flash device initialized successfully. sfud_flash name:norflash0 index:0 flash->spi.name QSPI1 sfud_flash_chip name:W25Q64JV capacity:0x00800000 mf_id ef type_id 40 capacity_id 17 erase_gran 4096 [D/FAL] (fal_flash_init:47) Flash device | norflash0 | addr: 0x00000000 | len: 0x00800000 | blk_size: 0x00001000 |initialized finish. [I/FAL] ==================== FAL partition table ==================== [I/FAL] | name | flash_dev | offset | length | [I/FAL] ------------------------------------------------------------- [I/FAL] | fdb_kvdb1 | norflash0 | 0x00000000 | 0x00040000 | [I/FAL] | fdb_tsdb1 | norflash0 | 0x00040000 | 0x00040000 | [I/FAL] ============================================================= [I/FAL] Flash Abstraction Layer (V0.5.99) initialize success. [FlashDB][kv][env][fdb_kvdb1] (E:/Clion_code/STM32_Clion/STM32H7_SFUD_clion/Module_Library/FlashDB/src/fdb_kvdb.c:1801) The oldest addr is @0x00000000 [FlashDB][kv][env][fdb_kvdb1] (E:/Clion_code/STM32_Clion/STM32H7_SFUD_clion/Module_Library/FlashDB/src/fdb_kvdb.c:1817) KVDB size is 262144 bytes. [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (goot_count@0x00000010) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (~emp@0x00000036) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (üemp@0x00000055) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (ÿemp@0x00000074) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (emp@0x00000094) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (goot_count@0x000000B4) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (ÿoot_count@0x00000100) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (boot_count@0x00000126) CRC32 check failed! [FlashDB] FlashDB V2.1.1 is initialize success. [FlashDB] You can get the latest version on https://github.com/armink/FlashDB . [FlashDB][sample][kvdb][basic] ==================== kvdb_basic_sample ==================== [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (ooot_count@0x00000010) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (~emp@0x00000036) CRC32 check failed! [FlashDB][kv][env][fdb_kvdb1] Error: Read the KV (üemp@0x00000055) CRC32 check failed! 这个是什么原因呢
最新发布
06-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值