EFCore之Code First

定义实体类和数据库上下文

新建一个Web API项目,使用NuGet引入如下组件

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools

SqlServerContext 代码如下:

cs 复制代码
using Canteen.Services;
using EFCodeFirst.Models;
using Microsoft.EntityFrameworkCore;

namespace EFCodeFirst.Context
{
    public class SqlServerContext:DbContext
    {
        public SqlServerContext()
        {

        }
        public SqlServerContext(DbContextOptions<SqlServerContext> options) : base(options) { }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                var sqlServerConString = ConfigurationHelper.GetConfigValueByKey("ConnectionStrings:MSSQLDbConnection");// Gobal_Setting.Instance.GetSettingValue("ConnectionStrings:MSSQLDbConnection");
                optionsBuilder.UseSqlServer(sqlServerConString, sqlOptions =>
                {
                    sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null); // 连接重试策略
                });
            }
            base.OnConfiguring(optionsBuilder);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<T_Author>();
            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<T_Author> Author { get; set; } 
    }
}

添加Author代码:

cs 复制代码
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFCodeFirst.Models
{
    [Table("T_Author")]
    public class T_Author
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(20)]
        public string gName {  get; set; }

        [StringLength(50)]
        public string CardID { get; set; }

        /// <summary>
        /// 信息
        /// </summary>
        [NotMapped]
        public string Info { get => $"姓名:{gName},地址:{CardID}"; }
    }
}

在NuGet控制台中输入如下命令:

cs 复制代码
Add-Migration m1

然后更新数据库:

cs 复制代码
Update-Database

数据库里会添加表T_Author

相关推荐
费曼学习法几秒前
12 个工具调用改成并发,耗时从 94 秒掉到 23 秒:DeepSeek 并行调用工程细节
前端
修炼的dance5 分钟前
qpdf四个结构开关逐个开,只有对象流明显省
前端
测试员周周8 分钟前
【agent评测】:真实系统演示工具调用长什么样,用例怎么设计,怎么测
前端·后端·github
张明君6445120 分钟前
在 Astro SSR 项目中实现服务启动前初始化
前端·后端
再吃一根胡萝卜1 小时前
从零实现 DSH 用户信息插件
前端
stormsha1 小时前
我的抓取脚本凭什么从不抢你的鼠标
前端·chrome
verohh1 小时前
尾言:关于前端工程架构设计的一些思考
前端
SameX1 小时前
HarmonyOS ArkTS 做 MBTI 风格 16 人格测评用 4 维签名字符串做分类的最小算法
前端
MiniToolDesk1 小时前
告别前端运行时 undefined:用 Zod 打造端到端类型守卫(附 JSON 一键生成实战)
前端
椒哥2 小时前
伪造一份"浏览器身份证":sdenv 是怎么骗过环境检测的
前端