美文网首页
EF Core 初始化数据库

EF Core 初始化数据库

作者: elef | 来源:发表于2019-03-15 17:40 被阅读0次

首先添加引用

$ 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

数据库及相关库表创建完成

相关文章

网友评论

      本文标题:EF Core 初始化数据库

      本文链接:https://www.haomeiwen.com/subject/ejurmqtx.html