EFCore--->> CodeFirst (Vs2019 Core3.0)的简单使用

直接上干货

EFCore--->> CodeFirst (Vs2019 Core3.0)

1: 安装下面3个对应的package(在Nuget控制台或者直接NuGet包查询点击下载,我喜欢下面的命令,B格一些)

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools


2:创建实体
namespace WebApplication1.Models
{
using System.ComponentModel.DataAnnotations;
public class Person
{
[Key] //将来在数据库对应的表中 就是主键
public int ID { get; set; }

[MaxLength(30), Required] //。。。
public string Name { get; set; }

public int? Age { get; set; } //可为空
public DateTime? Birthday { get; set; }
}
}

3: 覆写下面两个方法或其中一个方法,及新增俩个实体,并添加到这里
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
using Microsoft.EntityFrameworkCore;
public class TestDbContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//base.OnConfiguring(optionsBuilder);
string sqlConnection = "server=XB-201907130929\\ZRFSQLSERVER;uid=sa;pwd=123456;database=TestDbContext";
optionsBuilder.UseSqlServer(sqlConnection);
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<Person>().HasIndex(u => u.Name).IsUnique(); //是否唯一,看你直接是否需要咯
}

public DbSet<Person> Person { get; set; }
public DbSet<Book> Book { get; set; }
}
}


4:控制台命令:
Add-Migration Init //其中Init是你的版本名称 ,这个每一次修改都会要求你加上名称

下面update-database init会同步并生成数据库及表; init当做为版本号即可

update-database Init //再一次执行会回到这个数据库的版本包括表的字段和数据

update-database uupdte0 会更新到这个版本,数据库中的表都会更新到这个迁移的版本,包括数据

5:注意点
Add-Migration EditPwdLength // 修改了表或者添加了表
update-database EditPwdLength //加上版本EditPwdLength 会比较保险一些吧

后续会不断的写些自己的小笔记,加油!!!

猜你喜欢

转载自www.cnblogs.com/Fengge518/p/11446817.html