首先添加引用
$ dotnet add package Microsoft.EntityFrameworkCore
$ dotnet add package Microsoft.EntityFrameworkCore.SqlServer
# 下面这个主要做数据迁移时必须添加
$ dotnet add package Microsoft.EntityFrameworkCore.Design
创建业务类 Student.cs
using System;
namespace efcoredemo1
{
public class Student
{
public int Id { get; set; }
public int Age { get; set; }
public byte Status { get; set; }
public string Name { get; set; }
public DateTime CreatedTime { get; set; }
}
}
创建数据库上下文 EFCoreDbContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace efcoredemo1
{
public class EFCoreDbContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString =
"Data Source=192.168.10.1,1433;Integrated Security=false;Initial Catalog=db2;User Id = user1;Password = userpassword1;";
optionsBuilder.UseSqlServer(connectionString);
}
public DbSet<Student> Students { get; set; }
}
}
将当前工作目录设置为项目目录,输入如下命令
$ dotnet ef migrations add DbInit -c EFCoreDbContext -o Data/Migrations
$ dotnet ef database update -c EFCoreDbContext
数据库及相关库表创建完成
网友评论