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

相关推荐
phltxy19 小时前
Vue 核心特性实战指南:指令、样式绑定、计算属性与侦听器
前端·javascript·vue.js
Byron070720 小时前
Vue 中使用 Tiptap 富文本编辑器的完整指南
前端·javascript·vue.js
css趣多多20 小时前
地图快速上手
前端
zhengfei61120 小时前
面向攻击性安全专业人员的一体化浏览器扩展程序[特殊字符]
前端·chrome·safari
码丁_11721 小时前
为什么前端需要做优化?
前端
Mr Xu_21 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
Byron070721 小时前
从 0 到 1 搭建 Vue 前端工程化体系:提效、提质、降本实战落地
前端·javascript·vue.js
哆啦code梦21 小时前
前端存储三剑客:localStorage、sessionStorage与Cookie解析
前端·前端存储
徐小夕@趣谈前端1 天前
Web文档的“Office时刻“:jitword共建版2.0发布!让浏览器变成本地生产力
前端·数据结构·vue.js·算法·开源·编辑器·es6
Data_Journal1 天前
如何使用 Python 解析 JSON 数据
大数据·开发语言·前端·数据库·人工智能·php