1. 程式人生 > 其它 >EF Core DBFirst和CodeFirst 模式使用方法

EF Core DBFirst和CodeFirst 模式使用方法

一、安裝依賴包

1、Microsoft.EntityFrameworkCore

2、Microsoft.EntityFrameworkCore.Tools

3、Microsoft.EntityFrameworkCore.SqlServer

二、模式選擇

1、DBFirst 模式

1)新建資料庫指令碼並執行

2)開啟程式包管理控制檯生成DbContext上下文以及實體Model

scaffold-dbcontext "server=.;database=dbfirst;uid=sa;pwd=123456;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

3)配置Startup 類註冊DbContext上下文

services.AddDbContext<CodeFirstContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("ConStr"));
});

4)配置appsettings.json檔案

"ConnectionStrings": {
    "ConStr": "Server=localhost;Database=CodeFirst;Uid=sa;Pwd=Dennis374627149;"
  }

5)Controller中依賴注入就可以使用了

private readonly DbContextOptions<CodeFirstContext> _context;

public WeatherForecastController(ILogger<WeatherForecastController> logger, DbContextOptions<CodeFirstContext> context)
{
    _logger = logger;
    _context = context;
}

using (var context = new CodeFirstContext(_context))
{
    var model = context.UserEntities.FirstOrDefault(p => p.UserId.Equals("14"));
    if (model != null) return model.UpdateTime.ToString();
    return "";
}

2、Code First 模式

1)新建實體類Model

[Table("Users")]
public class UserEntity
{
    [Key]
    [Required]
    [StringLength(32)]
    public string UserId { get; set; }

    [Required]
    [StringLength(20)]
    public string Name { get; set; }
    [StringLength(20)]
    public int Age { get; set; }
    [StringLength(11)]
    public string Tel { get; set; }
    [StringLength(11)]
    public DateTime Birthday { get; set; }

    [Required]
    public DateTime CreateTime { get; set; }
    [Required]
    public DateTime UpdateTime { get; set; } = DateTime.Now;
}

2)新建DbContext上下文類,繼承DbContext

public class CodeFirstContext:DbContext
{
    public CodeFirstContext()
    {
    }
    public CodeFirstContext(DbContextOptions<CodeFirstContext> options) : base(options)
    {
    }
    public DbSet<UserEntity> UserEntities { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }
}

3)Startup注入和appsettting.json檔案同上

4)開啟程式包控制檯(CodeFirstTest 自定義名稱,如提示To undo this action, use Remove-Migration 代表初始化成功)

Add-Migration CodeFirstTest

5)繼續(更新最後一次遷移)

update-database

6)遷移完成