document/文档/.net/EfCode.md
2024-07-30 15:37:14 +08:00

2.2 KiB

反向工程

  1. 安装 dotnet tool install --global dotnet-ef
  2. 安装包 Microsoft.EntityFrameworkCore.Design
  3. 执行命令 dotnet ef dbcontext scaffold "Server=172.27.27.12;Database=TextGenerationTest;User Id=zpc;Password=zpc;TrustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -o Models --force

dotnet ef dbcontext scaffold "Server=192.168.195.2;Database=MiaoYu;User Id=zpc;Password=zpc;TrustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -o DbSqlServer/Db_MiaoYu/ --use-database-names --no-pluralize --force

  1. dotnet ef dbcontext scaffold "Name=ConnectionStrings:SunnySports_SqlServer_Db_SunnySport" Microsoft.EntityFrameworkCore.SqlServer --no-pluralize --force --output-dir ../../0-core/SunnySports.Model/DbSqlServer/Db_SunnySports/ --use-database-names --project ../../0-core/SunnySports.Model/

dotnet ef dbcontext scaffold "Name=ConnectionStrings:SunnySports_SqlServer_Db_Student" Microsoft.EntityFrameworkCore.SqlServer --no-pluralize --force --output-dir ../../0-core/SunnySports.Model/DbSqlServer/Db_Student/ --use-database-names --project ../../0-core/SunnySports.Model/

自定义模板

  1. dotnet new install Microsoft.EntityFrameworkCore.Templates
  2. dotnet new ef-templates

开启事务

  1. Read Uncommitted: 允许读取未提交的数据(脏读),几乎没有锁定。
  2. Read Committed: 只能读取已提交的数据(默认隔离级别),在读取数据时会使用共享锁,防止脏读。
  3. Repeatable Read: 确保在事务期间读取的数据一致,防止不可重复读,会对读取的数据使用锁。
  4. Serializable: 最严格的隔离级别,确保事务之间完全隔离,防止幻读,会对整个范围进行锁定。

//using (var transaction = context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable)) 事务等级
using (IDbContextTransaction transaction = context.Database.BeginTransaction())
{
    try
    {
        // 执行一些数据库操作
        
        context.SaveChanges();

       
        context.SaveChanges();

        // 提交事务
        transaction.Commit();
    }
    catch (Exception ex)
    {
        // 出现异常,回滚事务
        transaction.Rollback();
    }
}