Install-Package Microsoft.EntityFrameworkCore Install-Package MySql.EntityFrameworkCore //如果是mysql Install-Package Microsoft.EntityFrameworkCore.SqlServer //如果是mssql
using AntVue3Demo.Models; using Microsoft.EntityFrameworkCore; public class DbEntitys : DbContext { /// <summary> /// 配置连接字符串,每次访问数据库之前会自动执行此方法,在这里配置连接字符串 /// 相当于连接前事件 /// 使用 IOC 注入的方式不实现此方法 /// </summary> /// <param name="builder"></param> protected override void OnConfiguring(DbContextOptionsBuilder builder) { // 连接字符串 string ConnString = "Server=101.33.219.205;Database=AntVue3DemoDB;User ID=sa;Password=memeda999;"; // 连接SqlServer builder.UseSqlServer(ConnString); // 连接MySql //builder.UseMySql(ConnString); } /// <summary> /// 默认构造函数 使用方法与原来一样 /// </summary> public DbEntitys() : base() { } /// <summary> /// 通过IOC /// </summary> /// <param name="options"></param> public DbEntitys(DbContextOptions<DbEntitys> options) : base(options) { } #region 表映射 public virtual DbSet<Tabs> Tab1 { get; set; } #endregion }
3.根据模型映射建库(CodeFist生成库)
Install-Package Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate(名称可自定义) Update-Database
或手动创建Model映射表类,并体现在上下文链接类中
4.Program.cs文件的跨域配置
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //跨域配置 builder.Services.AddCors(options => { options.AddPolicy (name: "kuayu", builde => { builde.WithOrigins("*", "*", "*") .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); } ); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthorization(); app.UseCors("kuayu"); app.MapControllers(); app.Run();
5.在需要跨域的控制器文件中加入
[EnableCors("kuayu")] [Route("api/[controller]")]
本文作者:烈焰大火龙
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 © 烈焰大火龙 许可协议。转载请注明出处!