sql数据库的相关配置

Nuget包

第一步 创建好实体类

第二步 创建MyDbContext

 public class MyDbContext : DbContext
 {
     /////添加sql的记录
     public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
     ////从Program.cs可调取
     public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
     {

     }
     /// <summary>
     /// optionsBuilder.UseLoggerFactory(MyLoggerFactory) 记录efcore 的操作sql语句
     /// </summary>
     /// <param name="optionsBuilder"></param>
     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseLoggerFactory(MyLoggerFactory);

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         //实体类的相关配置


     }
     public virtual DbSet<User> Users { get; set; }
 }

第三步 appsettings.json 添加设置

"ConnectionStrings": {
  "SqlConnection": "data source=;database=;uid=;pwd=;Max pool Size=100; Min pool Size=5;Pooling=true;Persist Security Info=True;Encrypt=True;TrustServerCertificate=True;" 
},

第四步 Program.cs

    builder.Services.AddDbContext<MyDbContext>(opt =>
    {
        string? connStr = builder.Configuration.GetConnectionString("SqlConnection");
        opt.UseSqlServer(connStr);
    });

这样就完成了sql数据库的相关配置

添加控制器代码

[Route("api/[controller]/[action]")]
[ApiController]

public class DemoController : ControllerBase
{
    private readonly MyDbContext db;
    public DemoController(MyDbContext db) 
    {
        this.db = db;
    }
    [HttpGet]
    
    public int GetCount() 
    {
        return db.Users.Count(); 
    
    }

    [HttpGet]
    public async Task<Users> GetListById(int id) 
    {
        var a = await db.Users.Where(y => y.ID==id).SingleOrDefaultAsync();
        return a;
    }

   
}

redis相关配置

Nuget包

第一步 appsettings.json

  "ConnectionStrings": {
    "RedisConnection": "localhost"//链接本地的redis
    //"RedisConnection": "xxxx,password=xxxx"
  },

第二步 Program.cs

builder.Services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("RedisConnection")));

添加控制器代码

public class RedisController : ControllerBase
{
    private readonly IDatabase _redis;

    public RedisController(IConnectionMultiplexer redis)
    {
        _redis = redis.GetDatabase() ?? throw new ArgumentNullException(redis.GetDatabase().ToString());
    }

    [HttpGet]
    public string get(string key,string value) 
    {
        // 往Redis里面存入数据
        _redis.StringSet(key, value);
        // 从Redis里面取数据
        return _redis.StringGet(key);
        
    }
}

更多推荐