.netcore初体验

Asp.net Core 2.1使用 EF Core 简单增删改查操作数据库 大概步骤如下5步:

1、创建项目(Asp.net Core 2.1项目)

2、项目使用EF Core

3、建立实体

4、生成迁移文件(生成数据库)

5、使用VS工具生成视图、控制器代码

 示例代码下载  https://github.com/ZhMartincheng/NetCoreDemo.git

1、创建项目(Asp.net Core 2.1项目)

 技术分享图片

选择.net core 版本2.1

技术分享图片

 基础项目创建成功技术分享图片

2、项目使用EF Core

2.1、通过nuget 安装Microsoft.EntityFrameworkCore.SqlServer

项目右键管理nuget包

技术分享图片

技术分享图片

 安装成功

技术分享图片

3、建立实体

 

 

班级实体(一个班级多个学生)

 public class ClassEntiy
    {

        public int ID { get; set; }

        public string ClassName { get; set; }


        public virtual ICollection<Student> Students { get; set; }

    }

  技术分享图片

 

4、生成迁移文件(生成数据库)

 配置链接字符串 "ConnectionStrings": {"SqlServer": "Data Source=.;Initial Catalog=TestDb;User Id=sa;Password=123;"}

技术分享图片

创建 上下文对象 DbContext 

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetCoreDemo.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }
        public DbSet<Student> Student { get; set; }
        public DbSet<ClassEntiy> ClassEntitys { get; set; }
    }
}

 技术分享图片

代码配置数据库链接串

var connection = Configuration.GetConnectionString("SqlServer");
services.AddDbContext<NetCoreDemo.Models.ApplicationDbContext>(options =>
options.UseSqlServer(connection, b => b.MigrationsAssembly("NetCoreDemo")));

  

技术分享图片

 编译成功后执行生成迁移文件命令add-Migration Init

技术分享图片

通过迁移文件生成数据库Update-Database

技术分享图片

技术分享图片

数据库生成成

注册容器

构造函数注入

数据访问层

原文地址:https://www.cnblogs.com/KyrieCC/p/9985442.html