.Net Core EF CodeFirst

1、引用组件

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

2、设置连接数据库字符串

配置 appsettings.json,添加 “ConnectionStrings"

{
  "ConnectionStrings": {
    "book": "Data Source=localhost;Initial Catalog=wlw1902ABook;Persist Security Info=True;User ID=sa;Password=sa1234"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

3、创建Model

3.1 BookType (图书分类)

[Table("BookType")]
public class BookType
{
    [Key]
    public int TypeId { get; set; }

    [Required]
    [MaxLength(30)]
    public string TypeName { get; set; }
}

3.2 Book (图书信息)

    [Table("Book")]
    public class Book
    {
        [Key]
        public int BookId { get; set; }

        [Required]
        [MaxLength(30)]
        public string BookName { get; set; }

        [Required]
        public decimal Price { get; set; }

        [Required]
        [MaxLength(20)]
        public string Author { get; set; }

        [Required]
        public DateTime PublishedDate { get; set; }

        [Required]
        public int TypeId { get; set; }

        [ForeignKey("TypeId")]
        public virtual BookType BookType { get; set; }
    }

4、创建数据上下文

public class BookDbContext : DbContext
{
    // 构造函数(构造方法)
    public BookDbContext(DbContextOptions<BookDbContext> options) : base(options)
    {
    }

    // 映射(生成数据库中的表)
    public DbSet<BookType> BookTypeSet { get; set; }
    public DbSet<Book> BookSet { get; set; }
}

5、StartUp中配置数据上下文

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // 配置数据库上下文
    // 数据库连接字符串
    string strConn = Configuration.GetConnectionString("book");
    services.AddDbContext<BookDbContext>(options => options.UseSqlServer(strConn));
}

6、数据迁移

6.1、 add-migration 备份名称 firstCreateBookInfo

6.2、update-database

7、使用EF

.Net Core EF CodeFirst

.Net Core EF CodeFirst

上一篇:js大数字转换,将大额数字转换为万、千万、亿等


下一篇:ubuntu20.04系统下更新Raspberry Pi4的DTB