其他分享
首页 > 其他分享> > EF Core环境搭建

EF Core环境搭建

作者:互联网

EF Core环境搭建

  1. 实体类
  2. Config 配置类
  3. 创建继承DbContext的类 (设置连接数据库字符串)
  4. 自动生成数据库 (命令)
  5. 编写调用EF Core的业务代码

引入NuGet包

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.SqlServer.Design

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore
{
   public class Book
    {
        public long Id { get; set; }    //编号
        public string Title { get; set; }  //标题
        public DateTime dateTime { get; set; }  //发布日期
        public double Price { get; set; }   // 单价

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace EFCore
{
    class BookConfig : IEntityTypeConfiguration<Book>
    {
        public void Configure(EntityTypeBuilder<Book> builder)
        {
            builder.ToTable("T_Books"); 
        }
    }
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore
{
    class TestContext : DbContext
    {
        public DbSet<Book> Books { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //数据库连接字符串
            string connStr = "Data Source=.;Initial Catalog=demo1;Integrated Security=True"; 
            
            optionsBuilder.UseSqlServer(connStr);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }

    }
}

Add-Migration FirstMigration

​ 会自动在项目的Migrations文件夹中生成操作数据库的 C# 代码。( FirstMigration 提交变更的名字)

Update-Database

标签:Core,get,EF,System,Microsoft,EntityFrameworkCore,using,public,搭建
来源: https://www.cnblogs.com/pinkguy/p/15815408.html