随笔 - 9  文章 - 0 评论 - 2 阅读 - 3229
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

注释型实体映射属性

[Table("USER_T")] //指点表名称
[Column("blog_id")] //列名
[Column(TypeName = "varchar(200)")]
[Column(TypeName = "decimal(5, 2)")] //数据类型
[MaxLength(500)] //字符串最大长度,默认类型为nvarchar(500)
[Precision(3)]  //可定义DateTime类型
[Precision(14, 2)]   //精度和小数位

约束
[Required] //字符串非空

[Key] //主键
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //设置自增

public Datetime? CreatedTime{get;set;} //?代表时间格式可以为空

public bool CacheDbResults { get; set; } = true; //设置默认值

[NotMapped] //标识不映射到数据库字段

还可以通过Fluent API方式显示设置实体映射属性

注册数据库连接方式一,构造函数创建DbContext。依赖注入

1.在appsettings.json中添加连接字符串
1
2
3
4
5
6
7
8
9
10
11
12
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ctwContext": "Data Source=ctw.db"
  }
}

 2.在启动文件中注册

// Add services to the container.
builder.Services.AddRazorPages();

//builder.Services.AddDbContext<MyContext>();
builder.Services.AddDbContext<MyContext>(options =>
  options.UseSqlite(builder.Configuration.GetConnectionString("ctwContext")));

3.创建继承DbContext

复制代码
 public class MyContext : DbContext
    {
        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    optionsBuilder.UseSqlite("Data Source=ctw.db");
        //}
        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        {
        }
        public DbSet<User>? Users { get; set; }       

    }
复制代码

4.通过构造函数创建DbContext

复制代码
public class IndexModel : PageModel
    {
        private readonly Models.MyContext _context;
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger, Models.MyContext context)
        {
            _logger = logger;
            _context = context;
        }

        public void OnGet()
        {

        }
    }
复制代码
注册数据库连接方式二,new新建DbContext。连接多数据库情况
1.创建继承DbContext
复制代码
public class MyContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=ctw.db");
        }
        //public MyContext(DbContextOptions<MyContext> options)
        //    : base(options)
        //{
        //}
        public DbSet<User>? Users { get; set; }       

    }
复制代码

2.在启动文件中注册

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<MyContext>();
//builder.Services.AddDbContext<MyContext>(options =>
//  options.UseSqlite(builder.Configuration.GetConnectionString("ctwContext")));

var app = builder.Build();

3.new调用

复制代码
public class IndexModel : PageModel
    {
        //private readonly Models.MyContext _context;
        private readonly ILogger<IndexModel> _logger;

        //public IndexModel(ILogger<IndexModel> logger, Models.MyContext context)
        //{
        //    _logger = logger;
        //    _context = context;
        //}
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            using var context = new Models.MyContext();
            IQueryable<Models.User> blogs = context.Users;
        }
    }
复制代码

 启动ef core数据迁移

1.先安装Microsoft.EntityFrameworkCore.Tools

安装包时注意版本一致!并不是所有包都要是最新

tools包含的全部命令
Add-Migration
Bundle-Migration
Drop-Database
Get-DbContext
Get-Migration
Optimize-DbContext
Remove-Migration
Scaffold-DbContext
Script-Migration
Update-Database

2.Add-Migration xx //添加迁移,xx代表迁移名称

3.Update-Database //更新到数据库


(代码迁移)如果要删除某迁移类文件,最好先将数据库回滚到此迁移的上一版本,再删除
update-database -TargetMigration: [name] 命令,其中 [name] 要使用带时间戳的全名 

 

posted on   雾夜飞虫  阅读(723)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示