EF Core环境搭建
作者:互联网
EF Core环境搭建
- 实体类
- Config 配置类
- 创建继承DbContext的类 (设置连接数据库字符串)
- 自动生成数据库 (命令)
- 编写调用EF Core的业务代码
引入NuGet包
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer.Design
- 实体类-Book.cs
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; } // 单价
}
}
- 配置类-BookConfig.cs 数据表名
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");
}
}
}
- TestContext.cs 设置数据库连接字符串 Context类
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);
}
}
}
- 打开NuGet程序包管理控制台 输入
Add-Migration FirstMigration
会自动在项目的Migrations文件夹中生成操作数据库的 C# 代码。( FirstMigration 提交变更的名字)
Update-Database
标签:Core,get,EF,System,Microsoft,EntityFrameworkCore,using,public,搭建 来源: https://www.cnblogs.com/pinkguy/p/15815408.html